我找不到从JObject获取json数组列表的正确方法。
数组中的_name
元素应等于foo
。
这是示例json:
{
"doc": [{
"bob": [{
"tom": [{
"frank": [{
"category": [{
"_name": "foo",
"letters": "abc"
},
{
"_name": "foo",
"letters": "def"
},
{
"_name": "foo",
"letters": "ghi"
},
{
"_name": "foo",
"letters": "jkl"
}]
}]
}]
}]
}]
}
到目前为止,这是我的代码:
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;
我收到此错误:
"Value cannot be null.\r\nParameter name: source"
如何获得一个列表,其中每个元素都是包含“_name”和“letters”的数组?
答案 0 :(得分:3)
三个问题:
doc
的直接孩子,你想要后代。x["_name"].Value<string>()
属性_name
x["_name"].Value<string>()
这些都很容易修复:
var doc = (JContainer) o["doc"];
var results = doc.Descendants()
.OfType<JObject>()
.Where(x => x["_name"] != null &&
x["_name"].Value<string>() == "foo");