Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first child of JObject without using foreach loop

Tags:

json

c#

json.net

I need to get the first child of JObject. This is how I temporarily solved it with foreach loop breaking after first iteration.

foreach (KeyValuePair<string, JToken> item in (JObject)json["stats"])
{
    // doing something with item
    break;
}

I wonder if there is shorter solution, like json["stats"][0] (however it doesn't work this way).

like image 245
stil Avatar asked Jan 16 '15 19:01

stil


People also ask

How do you iterate over a JObject?

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.

How do I get JArray JObject?

FirstOrDefault(o => o["text"] != null && o["text"]. ToString() == "Two"); This will find the first JObject in the JArray having a property named text with a value of Two .

How do I find my JObject key?

You can simply convert the JObject into a Dictionary object and access the method Keys() from the Dictionary object. Like this: using Newtonsoft. Json.


3 Answers

There are probably a few ways, but here's one:

JToken prop = obj["stats"].First;

If you know it's a JProperty:

JProperty prop = obj["stats"].First.ToObject<JProperty>();
like image 194
Andrew Whitaker Avatar answered Sep 18 '22 09:09

Andrew Whitaker


Since JObject implements IDicionary<string, JToken> you can use Linq extension methods.

 IDictionary<string, JToken> json = new JObject();
 var item = json.First();
like image 37
hansmaad Avatar answered Sep 22 '22 09:09

hansmaad


Wouldn't this work?

(json["stats"] as JObject).Select(x =>
      {
            // do something with the item;

            return x;
      }).FirstOrDefault();
like image 27
Tejs Avatar answered Sep 21 '22 09:09

Tejs