2

I have a JSON string: [{"number":"123-456-789","array":["1", "2"]}]. I want check to see if this JSON contains a "number" field. What I am trying:

string jsonString = [{"number":"123-456-789","array":["1", "2"]}];
Newtonsoft.Json.Linq.JArray jsonObject = JArray.Parse(jsonString);

How do I then "search" this jsonObject for a specified field?

7
  • once it's decoded, then it's some kind of native object, not a string. you'd use the same iteration methods for that object as you would any other. Commented Jun 30, 2014 at 18:44
  • @MarcB Can you give an example, please? Commented Jun 30, 2014 at 18:45
  • Feel free to recommend a method that does not rely on the "Newtonsoft" library :) Oh god, why? That's often considered THE best JSON library for .NET out there. Commented Jun 30, 2014 at 18:45
  • @mason Very well. I shall edit the post :) Commented Jun 30, 2014 at 18:46
  • Are you able to represent the JSON with a .NET POCO and use JavaScriptSerializer.Deserialize() ? see link Then it's a matter of inspecting the POCO. Commented Jun 30, 2014 at 18:51

2 Answers 2

5

If you would like to test if the "number" property exists, then you can use:

bool exists = jsonObject[0].Children<JProperty>().Any(p => p.Name == "number");

If you want to get the value of the "number" property, then you can use

string number = jsonObject[0]["number"].Value<string>();

Edit Here is how to get the "array" property

string[] arr = jsonObject[0]["array"].Values<string>().ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Like this:

        var isThereNumber = jsonObject[0]["number"];
        var isThereNumber2 = jsonObject[0]["number2"];

Cheers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.