Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through JSON using System.Json

Tags:

json

c#

.net-4.5

I'm exploring the capabilities of .NET 4.5 System.Json library but there isn't much documentation, and it's quite tricky to search for due to the popular JSON.NET library.

I am wondering basically, how I'd loop through some JSON for example:

{ "People": { "Simon" : { Age: 25 }, "Steve" : { Age: 15 } } }

I have my JSON in a string, and I want to iterate through and display the ages of everyone.

So first I'd do:

var jsonObject = JsonObject.Parse(myString);

but then I'm at a loss of what to do next. I'm surprised that the parse method returns a JsonValue not a JsonObject.

What I want to do really is:

foreach (var child in jsonObject.Children)
{
  if (child.name == "People")
{
 // another foreach to loop over the people
 // get their name and age, eg. person.Name and person.Children.Age (LINQ this or something)

}

}

any ideas?

like image 311
NibblyPig Avatar asked Nov 12 '22 06:11

NibblyPig


1 Answers

Since the accepted answer does not helped me much because its one of the typcial useles "use this lib its better!" answers i figured that out.

Yes,

JsonObject.Parse(myJsonString);

Returns a JsonValue object that is the base class of all the Json* classes from System.Json. When you call JsonObject.Parse(..) then JsonValue.Parse() is really being called because of the inheritance.

to iterate over a JsonObject you can use:

var jsonObject = JsonValue.parse(jsonString);

foreach (KeyValuePair<string, JsonValue> value in jsonObject)
{
    Console.WriteLine("key:" + value.Key);
    Console.WriteLine("value:" + value.Value);
}

I dont tried out if this also works if its an JsonArray but maybe if its an JsonArray then you might want to do it with a classic for i:

for (var i = 0; i < jsonObject.Count; i++)
{
    Console.WriteLine("value:" + jsonObject[i]);
}

If you dont know if its an array or an object than you might check that before

if (jsonObject.GetType() == typeof JsonObject){
    //Iterate like an object 
}else if (jsonObject.GetType() == typeof JsonArray){
    //iterate like an array
}
like image 174
Salmakis Avatar answered Nov 15 '22 08:11

Salmakis