How do I parse a JSON object in C# when I don't know the key in advance?
I have some JSON data that looks like this:
{
"910719": {
"id": 910719,
"type": "asdf",
"ref_id": 7568
},
"910721": {
"id": 910721,
"type": "asdf",
"ref_id": 7568
},
"910723": {
"id": 910723,
"type": "asdf",
"ref_id": 7568
}
}
How can I parse this using JSON.net? I can first do this:
JObject jFoo = JObject.Parse(data);
I need to be able to iterate over each object in this list. I would like to be able to do something like this:
foreach (string ref_id in (string)jFoo["ref_id"]) {...}
or
foreach (JToken t in jFoo.Descendants())
{
Console.WriteLine((string)t["ref_id"]);
}
but of course that doesn't work. All the examples work great if you know the key while writing your code. It breaks down when you don't know the key in advance.
Solution 1:
It's doable; this works but it's not elegant. I'm sure there's a better way.
var o = JObject.Parse(yourJsonString);
foreach (JToken child in o.Children())
{
foreach (JToken grandChild in child)
{
foreach (JToken grandGrandChild in grandChild)
{
var property = grandGrandChild as JProperty;
if (property != null)
{
Console.WriteLine(property.Name + ":" + property.Value);
}
}
}
}
Prints:
id:910719 type:asdf ref_id:7568 id:910721 type:asdf ref_id:7568 id:910723 type:asdf ref_id:7568
Solution 2:
You can iterate over the child objects with a simple LINQ query like this:
JObject jFoo = JObject.Parse(json);
foreach (JObject obj in jFoo.Properties().Select(p => p.Value))
{
Console.WriteLine("id: " + obj["id"]);
Console.WriteLine("type: " + obj["type"]);
Console.WriteLine("ref_id: " + obj["ref_id"]);
}
Fiddle: https://dotnetfiddle.net/fwINPa
Or if you just want all the ref_id
values, you can do something like this:
string[] refIds = jFoo.Properties()
.Select(p => (string)p.Value["ref_id"])
.ToArray();
Console.Write(string.Join("\r\n", refIds));
Fiddle: https://dotnetfiddle.net/twOuVY
Solution 3:
I'm using Json.NET and I wrote a quick way where you can print out all of the keys and corresponding values using a recursive method.
var o = JObject.Parse(YourJsonString);
getAllProperties(o); //call our recursive method
Then you can use this recursive method to get all the Properties and their values
void getAllProperties(JToken children)
{
foreach (JToken child in children.Children())
{
var property = child as JProperty;
if (property != null)
{
Console.WriteLine(property.Name + " " + property.Value);//print all of the values
}
getAllProperties(child);
}
}
Solution 4:
Have you considered using JavascriptSerializer?
you could try do something like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var foo = serializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(data);
foreach(var item in foo)
{
Console.Writeln(item.Value["ref_id"]);
}
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx