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?

user3772119
  • 484
  • 3
  • 7
  • 16
  • 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. – Marc B Jun 30 '14 at 18:44
  • @MarcB Can you give an example, please? – user3772119 Jun 30 '14 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. – mason Jun 30 '14 at 18:45
  • @mason Very well. I shall edit the post :) – user3772119 Jun 30 '14 at 18:46
  • Are you able to represent the JSON with a .NET POCO and use JavaScriptSerializer.Deserialize() ? [see link](http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx) Then it's a matter of inspecting the POCO. – Mario J Vargas Jun 30 '14 at 18:51
  • uhh... This doesn't compile. You can't assign raw JSON to a string without making it a single string. Did you forget to wrap it in quotes? – Matt Johnson-Pint Jun 30 '14 at 19:00
  • Why don't use isNaN function on the desired field after convert with JSON.parse? – felipekm Jun 30 '14 at 19:07

2 Answers2

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();
Mike Hixson
  • 5,071
  • 1
  • 19
  • 24
1

Like this:

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

Cheers

Darek
  • 4,687
  • 31
  • 47