0

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.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Nguyen Diep
  • 85
  • 1
  • 9
  • why are you de-serializing to `dynamic` instead of a named class? Anyway you may just use `jss.value.Length`. – MakePeaceGreatAgain Oct 15 '21 at 09:03
  • a named class take time to write :( – Nguyen Diep Oct 15 '21 at 14:08
  • 1
    if it's okay for you to scratch your head in a few months because you cannot remember how your data-structure looks like only because you've been to lazy to invest a few seconds to extract a class from given data... it's your program. – MakePeaceGreatAgain Oct 15 '21 at 14:47
  • Agree with @HimBromBeere - I can't think of many times when developing in C# that I've had to use dynamic. Dynamic typing has it's place, but this isn't it – scottdavidwalker Oct 15 '21 at 20:25

2 Answers2

1

if you know the key you can do something like

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

Isparia
  • 682
  • 5
  • 20
1

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)

Yong Shun
  • 35,286
  • 4
  • 24
  • 46