使用JSON.net获取JToken的名称/密钥


81

我有一些看起来像这样的JSON

[
  {
    "MobileSiteContent": {
      "Culture": "en_au",
      "Key": [
        "NameOfKey1"
      ]
    }
  },
  {
    "PageContent": {
      "Culture": "en_au",
      "Page": [
        "about-us/"
      ]
    }
  }
]

我将其解析为JArray:

var array = JArray.Parse(json);

然后,我遍历数组:

foreach (var content in array)
{

}

content 是一个 JToken

如何检索每个项目的“名称”或“键”?

例如,“ MobileSiteContent”或“ PageContent”

Answers:


128

JToken是基类JObjectJArrayJPropertyJValue,等你可以使用Children<T>()的方法来获得JToken的孩子是某种类型的过滤列表,例如JObject。每个对象JObject都有一个JProperty对象集合,可以通过Properties()方法访问这些对象。对于每个JProperty,您都可以得到它Name。(当然,Value如果需要,您也可以获取,这是另一个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

23
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

22

JObject的默认迭代器是作为对键/值对进行迭代的字典。

JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
    Console.WriteLine (pair.Key);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.