Nguyen Diep
Nguyen Diep

Reputation: 85

How to count the length of value array in JSON

I have a JSON below:

{
  "value": [
    {
      "name": "504896c031d2fcb9",
      "location": "North Europe",
      "properties": {
        "state": "UNKNOWN",
        "name": "504896c031d2fcb9",
        "siteInstanceName": "504896c031d2fcb93ec",
        "healthCheckUrl": null,
        "machineName": "lw0s",
        "containers": null
      }
    },
    {
      "name": "35aafa",
      "location": "North Europe",
      "properties": {
        "state": "UNKNOWN",
        "name": "35aafae",
        "siteInstanceName": "35aafaeff",
        "healthCheckUrl": null,
        "machineName": "lw1s",
        "containers": null
      }
    }
  ],
  "nextLink": null,
  "id": null
}

I have converted JSON to a dynamic as mentioned below:

string kq = reader.ReadToEnd();
dynamic jss = JsonConvert.DeserializeObject(kq);

I want to know how to count how many values in C#? The above example has 2 values.

Thank you.

Upvotes: 0

Views: 2016

Answers (2)

Yong Shun
Yong Shun

Reputation: 51350

Cast as JArray and .Count.

Perhaps, if the value is not an array type, casted array will return as null.

You may add handling to check whether it is not null and get .Count.

dynamic jss = JsonConvert.DeserializeObject(kq);
JArray array = jss["value"] as JArray;
Console.WriteLine(array != null ? array.Count : 0);

Sample program (JsonConvert.DeserializeObject)


Recommendation:

Since you are deserializing JSON string to dynamic, with JsonConvert.DeserializeObject it will return the value of JObject type.

I would suggest using JObject.Parse rather than JsonConvert.DeserializeObject<T> (which is designed for converting to strongly-type object).

You may read this question: JObject.Parse vs JsonConvert.DeserializeObject for more info.

using Newtonsoft.Json.Linq;

JObject jss = JObject.Parse(json);
JArray array = jss["value"] as JArray;
Console.WriteLine(array != null ? array.Count : 0);

Sample program (JObject.Parse)

Upvotes: 1

Isparia
Isparia

Reputation: 712

if you know the key you can do something like

 dynamic jss = JsonConvert.DeserializeObject(kq);
 jss["value"].Count

Upvotes: 1

Related Questions