Search code examples
c#jsonjson.net

How do I enumerate nested JObject using JSON.net?


I have a stringified json object which I parse using JObject.Parse and get the result below-

{{
   "payload": {
       "firstName": "John",
       "lastName": "Doe"
    }
}}

This was my input -

"{ \r\n\"payload\": {\r\n\t\"firstName\":\"John\", \r\n\t\"lastName\": \"Doe\"\r\n }}"

The extra brackets are the start and the end are added by the parser. I want to iterate over this object and display the key value for first name and last name.

foreach (var property in jobject)
{
    Console.WriteLine("  {0}: {1}", property.Name, property.Value);
}

However, I don't know because of the two brackets or because of the nested structure I cannot get to the properties inside. I tried a recursive approach to parse the json but haven't been successful yet. Can someone please help me with this?


Solution

  • If you want to iterate all nested objects as well you can do something like this:

    var p = JObject.Parse(...);
    foreach (var a in p.DescendantsAndSelf())
    {
        if (a is JObject obj)
            foreach (var prop in obj.Properties())
                if (!(prop.Value is JObject) && !(prop.Value is JArray))
                    Console.WriteLine("  {0}: {1}", prop.Name, prop.Value);
    }