Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count Number of Elements in JSON string with Json.NET in C#

Tags:

json

c#

json.net

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'm using the Json.NET LINQ to JSON functionality to handle my JSON string, but I'm wondering how I can find the total number of nodes/elements/keys (I'm not really sure what to call them) in my string. For example, the above string has package1 and package2 so I'm wondering how I can get it to return the integer 2. Sometimes I might only have one package, in which case, I'd like it to return the integer 1. Other times I might have 20 packages (in that case I'd like it to return 20).

My JObject looks like this:

JObject o = JObject.Parse(myJsonString);

Any ideas? Thanks for any help.

like image 927
Brent Barbata Avatar asked Apr 03 '12 20:04

Brent Barbata


1 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);
}
like image 63
L.B Avatar answered Sep 25 '22 23:09

L.B