I'm having trouble finding the correct method for getting a list of json arrays from JObject.
_name
element inside the array should be equal to foo
.
This is the sample json:
{
"doc": [{
"bob": [{
"tom": [{
"frank": [{
"category": [{
"_name": "foo",
"letters": "abc"
},
{
"_name": "foo",
"letters": "def"
},
{
"_name": "foo",
"letters": "ghi"
},
{
"_name": "foo",
"letters": "jkl"
}]
}]
}]
}]
}]
}
And here's my code so far:
JObject o = JObject.Parse(File.ReadAllText(@"D:/Client/data.json"));
var results = from x in o["doc"].Children()
where x["_name"].Value<string>() == "foo"
select x;
I get this error:
"Value cannot be null.\r\nParameter name: source"
How do I get a list in which each element will be an array containing "_name" and "letters"?
Three problems:
doc
, you want the descendants.x["_name"].Value<string>()
even if there is no _name
propertyx["_name"].Value<string>()
even on non-object childrenThese are all easily fixed though:
var doc = (JContainer) o["doc"];
var results = doc.Descendants()
.OfType<JObject>()
.Where(x => x["_name"] != null &&
x["_name"].Value<string>() == "foo");
See more on this question at Stackoverflow