使用JSON.net获取JToken的名称/密钥 [英] Getting the name / key of a JToken with JSON.net

查看:316
本文介绍了使用JSON.net获取JToken的名称/密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的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);

然后,我遍历数组:

foreach (var content in array)
{

}

contentJToken

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

How can I retrieve the "name" or "key" of each item?

例如"MobileSiteContent"或"PageContent"

For example, "MobileSiteContent" or "PageContent"

推荐答案

JTokenJObjectJArrayJPropertyJValue等的基类.可以使用Children<T>()方法,以获取具有特定类型(例如JObject)的JToken子级的过滤列表.每个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的名称/密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆