Reputation: 5566
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).
Upvotes: 5
Views: 18496
Reputation: 418
You need to access to the "stats" by selecting token and access the first object in it.
var first = jo.SelectToken("stats").First;
Upvotes: 0
Reputation: 126072
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>();
Upvotes: 6
Reputation: 18905
Since JObject
implements IDicionary<string, JToken>
you can use Linq extension methods.
IDictionary<string, JToken> json = new JObject();
var item = json.First();
Upvotes: 2
Reputation: 41256
Wouldn't this work?
(json["stats"] as JObject).Select(x =>
{
// do something with the item;
return x;
}).FirstOrDefault();
Upvotes: 1