问题描述
如何使用 JSON.NET 从 JSON 中获取myThings"数组,如下所示?
How can I get the "myThings" array out of JSON that looks like the following using JSON.NET?
示例 1:
{
"z": {
"a": 1,
"b": 2
},
"something": {
"y": [1, 2],
"somethingElse": {
"1234": {
"foo": "bar",
"myThings": [{
"name": "bob",
"age": 3
}, {
"name": "bob",
"age": 3
}]
}
}
}
}
示例 2:
{
"z": {
"a": 1,
"b": 2
},
"something": {
"y": [1, 2],
"somethingElse": {
"7890": {
"foo": "bar"
}
}
}
}
我遇到困难的几件事:
- 其中一个属性名称是一个不可预测的数字(1234"和7890")
- 有时myThings"数组不存在 - 在这种情况下,我想要的是 null 或空数组/集合
另一个对你有帮助的考虑:我确实有一个静态类来表示 myThings 数组中的东西,所以我理想的返回值是 IEnumerable<MyThing>
Another consideration in case it helps you: I do have a static class that represents the things inside of the myThings array, so my ideal return value would be IEnumerable<MyThing>
我的第一次尝试是使用 JsonConvert.DeserializeObject<dynamic>(json)
但我不知道如何处理我上面提到的问题.最后,我不需要整个 JSON 字符串的数据,只需要名为myThings"的内部数组.
My first attempt was to use JsonConvert.DeserializeObject<dynamic>(json)
but I don't know how to handle the issues I mentioned above. In the end, I don't need the entire JSON string's worth of data, just that inside array named "myThings".
推荐答案
可以使用JToken.SelectTokens()
用于此目的.它允许使用通配符查询 JSON 并使用 JSONPath 语法进行递归搜索:
You can use JToken.SelectTokens()
for this purpose. It allows for querying JSON using wildcards and recursive searches using the JSONPath syntax:
var root = JToken.Parse(json);
var myThings = root.SelectTokens("..myThings[*]").ToList();
这里".."
是递归下降操作符,"myThings[*]"
表示返回属性的所有数组项myThings"
.
Here ".."
is the recursive descent operator and "myThings[*]"
means to return all array items of the property "myThings"
.
原型小提琴.
如果 "myThings[*]"
的数组条目对应一些 POCO MyThing
,则可以使用 JToken.ToObject
查询后反序列化:
If the array entries of "myThings[*]"
correspond to some POCO MyThing
, you can use JToken.ToObject<T>()
to deserialize them after querying:
var myThings = root.SelectTokens("..myThings[*]").Select(t => t.ToObject<MyThing>()).ToList();
这篇关于如何从 JSON 字符串中获取深度嵌套的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!