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).
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.
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 .
You can simply convert the JObject into a Dictionary object and access the method Keys() from the Dictionary object. Like this: using Newtonsoft. Json.
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>();
Since JObject
implements IDicionary<string, JToken>
you can use Linq extension methods.
IDictionary<string, JToken> json = new JObject();
var item = json.First();
Wouldn't this work?
(json["stats"] as JObject).Select(x =>
{
// do something with the item;
return x;
}).FirstOrDefault();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With