Count The number of elements in a JSON string with Json.NET in C #

I have a JSON string that looks like this:

{ "package1": { "type": "envelope", "quantity": 1, "length": 6, "width": 1, "height": 4 }, "package2": { "type": "box", "quantity": 2, "length": 9, "width": 9, "height": 9 } } 

I am using Json.NET LINQ to JSON to process my JSON string, but I am wondering how I can find the total number of nodes / elements / keys (I'm not sure how to name them) in my string. For example, the line above has package1 and package2, so I wonder how I can get it to return integer 2. Sometimes I can only have one package, in which case I would like it to return integer 1. Another time I could have 20 packages (in this case, I would like it to return 20).

My JObject looks like this:

 JObject o = JObject.Parse(myJsonString); 

Any ideas? Thanks for any help.

+8
json c #
source share
2 answers
 JObject jObj = (JObject)JsonConvert.DeserializeObject(myJsonString); int count = jObj.Count; 

BONUS:

 dynamic jObj = JsonConvert.DeserializeObject(myJsonString); foreach (var package in jObj) { Console.WriteLine("{0} {1}", package.First.type, package.First.quantity); } 
+16
source share

in jquery $ .ajax you get an array, go through the elements and get the amount.

-3
source share

All Articles