How do I enumerate through a JObject?
I'm trying to determine how to access the data that is in my JObject and I can't for the life of me determine how to use it.
JObject Object = (JObject)Response.Data["my_key"];
I can print it to the console doing Console.WriteLine(Object) and I see the data, it looks like:
{
"my_data" : "more of my string data"
...
}
But I have NO idea how to just iterate/enumerate through it, anyone have any ideas? I'm at such a loss right now.
If you look at the documentation for JObject
, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>
. So, you can iterate over it simply using a foreach
:
foreach (var x in obj)
{
string name = x.Key;
JToken value = x.Value;
…
}
JObjects can be enumerated via JProperty objects by casting it to a JToken:
foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
string name = x.Name;
JToken value = x.Value;
}
If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:
foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
string name = x.Name;
JToken value = x.Value;
}
The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.
This is the answer that worked for me:
foreach (var x in jobj)
{
var key = ((JProperty) (x)).Name;
var jvalue = ((JProperty)(x)).Value ;
}
For people like me, linq addicts, and based on svick's answer, here a linq approach:
using System.Linq;
//...
//make it linq iterable.
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
Now you can make linq expressions like:
JToken x = obj_linq
.Where( d => d.Key == "my_key")
.Select(v => v)
.FirstOrDefault()
.Value;
string y = ((JValue)x).Value;
Or just:
var y = obj_linq
.Where(d => d.Key == "my_key")
.Select(v => ((JValue)v.Value).Value)
.FirstOrDefault();
Or this one to iterate over all data:
obj_linq.ToList().ForEach( x => { do stuff } );