user3580480
user3580480

Reputation: 482

Access child objects from nested JSON

I have a JSON string, which is srtuctered as per the below.

"total": 5,
"filtered": 5,
"items": [
  {
  "assignedProducts": [
    "antivirus"
  ],
  "cloned": false,
  "device_encryption_status_unmanaged": false,
  "java_id": "2408cf5b-669c-434e-ac4c-a08d93c40e6a",
  "last_activity": "2019-09-20T12:36:22.175Z",
  "last_user_id": "5c6bc52305f05316ba18db06",
  "heartbeat_utm_name": null,
  "group_full_name": null,
  "is_adsync_group": false,
  "is_caching_proxy": false,
  "info": {
    "processor_architecture": "x64",
    "osMajorVersion": 10,
    "computer_name": "INDPC01",
    "isServer": false,
    "osInstallationType": "Client",
    "fqdn": "INDPC01",
    "osName": "Windows 10 Pro N",
  "id": "4280fcb5-66c9-34e4-cac4-0ad8394ce0a6",
  "name": "INDPC01"
},

I am using the following code to get values from a JSON string.

var resultObjects = AllChildren(JObject.Parse(response.Content))
        .First(c => c.Type == JTokenType.Array && c.Path.Contains("items"))
        .Children<JObject>();

    foreach (JObject result in resultObjects)
    {
        foreach (JProperty property in result.Properties())
        {
            ListBox1.Items.Add(property.Name.ToString() + " - " + property.Value.ToString());
        }
    }   
}

private static IEnumerable<JToken> AllChildren(JToken json)
{
    foreach (var c in json.Children())
    {
        yield return c;
        foreach (var cc in AllChildren(c))
        {
            yield return cc;
        }
    }
}

I am able to get all the values for everything within "Items", however I am not sure how to access the child JSON objects, for example the information under "info"

Upvotes: 0

Views: 1470

Answers (1)

user7217806
user7217806

Reputation: 2104

You can access childs using indexer, e.g.:

// ...

foreach (JObject result in resultObjects)
{
    var architecture = result["info"]["processor_architecture"].ToString();
    // ...
}

Note that it might be an easier approach to convert the JSON to an object, e.g. using JsonConvert, instead using JObject.Parse.

Upvotes: 1

Related Questions