1

In JSON.net, how do you iterate through the JProperties of a JObject key's children?

Code:

JObject json = JObject.Parse(jsonstring);
var developments = json["Developments"][0];

//Doesn't work
//Error   CS1929  'JToken' does not contain a definition for 'Properties' and the best extension method overload 'Extensions.Properties(IEnumerable<JObject>)' requires a receiver of type 'IEnumerable<JObject>'
//foreach(JProperty property in development.Properties())
//    Console.WriteLine(property.Name + property.Value);

JSON:

{
  "Developments": {
    "Plot 125": {
      "developer": "XYZ",
      "selection":{
        "Subdivision 1" : "135000",
        "Subdivision 2":  "450000"
      }
    },
    "Plot 126":{
      "developer": "XYZ",
      "selection":{
        "Subdivision 1": "56000",
        "Subdivision 2": "98000",
        "Subdivision 3": "456000"
      }
    }
  }
}

Compiled with JSON.net 4.0 version 6.0.0

Eugene
  • 10,957
  • 20
  • 69
  • 97

1 Answers1

6

All JToken objects contain properties that allow you to operate on any object as if it were any of the valid json types.

In json.net in particular, the children of objects are JProperty. So just get the children of the object.

var query =
    from x in json["Developments"].Children<JProperty>()
    select x.Name;

On the other hand, if it is already typed as a JObject, you could access the properties directly.

var query =
    from x in ((JObject)json["Developments"]).Properties()
    select x.Name;
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272