Reputation: 3122
I'm a bit confused with the Newtonsoft.Json JObject
interface. Say I need to access the 'foo'
property of the first child in my JSON object. My C# code:
string json = @"{
'someUnknownKey': { 'foo': 'bar' }
}";
JObject o = JObject.Parse(json);
JObject child = o.First.ToObject<JProperty>().Value.ToObject<JObject>();
string s = child["foo"].ToObject<string>();
This works, but is there a more elegant way to do it, without all the JProperty
/JObject
conversions?
EDIT: I would like to stress that the key name someUnknownKey
is unknown so I can't use it in my code.
Upvotes: 2
Views: 4370
Reputation: 4428
You can query the json object as dynamic:
string json = @"{
'someUnknownKey': { 'foo': 'bar' }
}";
dynamic o = JArray.Parse(json);
string child = o.someUnknownKey.foo;
Look here for a reference https://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
Alternatively you can use [] to access json properties:
JObject o = JObject.Parse(json);
string value = (string)(o['someUnknownKey']['foo']);
Upvotes: -1
Reputation: 17485
You can do something like this.
var jtk = o.Descendants().First().Children().First().Value<string>("foo")
Upvotes: 0
Reputation: 1502246
I believe you do need a conversion to indicate that you expect the first child token to be a property, but you can do it more simply than your current code:
string json = @"{
'someUnknownKey': { 'foo': 'bar' }
}";
JObject root = JObject.Parse(json);
Console.WriteLine(((JProperty) root.First).Value["foo"]);
Or to break it down slightly more clearly:
JObject root = JObject.Parse(json);
JProperty property = (JProperty) root.First;
Console.WriteLine(property.Value["foo"]);
Another option is to use the Properties()
method to ask for the first property instead of the first child token. That way you don't need any conversion.
JObject root = JObject.Parse(json);
Console.WriteLine(root.Properties().First().Value["foo"]);
Upvotes: 3