Home > OS >  How to count value in array json
How to count value in array json

Time:10-16

I have a JSON code 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.

CodePudding user response:

if you know the key you can do something like

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

CodePudding user response:

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)

  • Related