0

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"

2
  • That's not valid JSON for a start. Secondly, why not use a concrete set of classes for your data and deserialise properly? That way you will get compile time type checking. Commented Sep 27, 2019 at 15:17
  • Thanks for the feedback. The JSON is from a 3rd party API, which I have truncated for the sake of brevity, maybe that's why it does not appear to be valid? I did try to copy the JSON into Visual Studio to create the classes and have also tried to create them manually, but struggled to get the correct syntax for it to work Commented Sep 27, 2019 at 16:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that's exactly what I needed :)

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.