问题描述
我有一些像这样的 JSON
I have some JSON that looks like this
[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
我将其解析为 JArray:
I parse this as a JArray:
var array = JArray.Parse(json);
然后,我循环遍历数组:
Then, I loop over the array:
foreach (var content in array)
{
}
content
是一个 JToken
如何检索每个项目的名称"或密钥"?
How can I retrieve the "name" or "key" of each item?
例如,MobileSiteContent"或PageContent"
For example, "MobileSiteContent" or "PageContent"
推荐答案
JToken
是 JObject
, JArray
, 的基类>JProperty
、JValue
等.您可以使用 Children<T>()
方法获取某个 JToken 的子代的过滤列表类型,例如 JObject
.每个 JObject
都有一个 JProperty
对象的集合,可以通过 Properties()
方法访问这些对象.对于每个 JProperty
,您可以获得它的 Name
.(当然你也可以根据需要获取Value
,也就是另一个JToken
.)
JToken
is the base class for JObject
, JArray
, JProperty
, JValue
, etc. You can use the Children<T>()
method to get a filtered list of a JToken's children that are of a certain type, for example JObject
. Each JObject
has a collection of JProperty
objects, which can be accessed via the Properties()
method. For each JProperty
, you can get its Name
. (Of course you can also get the Value
if desired, which is another JToken
.)
综合起来我们有:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
输出:
MobileSiteContent
PageContent
这篇关于使用 JSON.net 获取 JToken 的名称/密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!