访问 JToken 中的所有项目 [英] Accessing all items in the JToken

查看:17
本文介绍了访问 JToken 中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的 json 块:

I have a json block like this:

{
    "ADDRESS_MAP":{

        "ADDRESS_LOCATION":{
            "type":"separator",
            "name":"Address",
            "value":"",
            "FieldID":40
        },
        "LOCATION":{
            "type":"locations",
            "name":"Location",
            "keyword":{
                "1":"LOCATION1"
            },
            "value":{
                "1":"United States"
            },
            "FieldID":41
        },
        "FLOOR_NUMBER":{
            "type":"number",
            "name":"Floor Number",
            "value":"0",
            "FieldID":55
        },
        "self":{
            "id":"2",
            "name":"Address Map"
        }
    }
}

如何获取此令牌包含的所有关键项目.例如,从上面的代码中,我想要 "ADRESS_LOCATION" 、 "LOCATION"、"FLOOR_NUMBER" 和 "self".

How can I get all the key items that this token includes. For example from the above code I want to have "ADRESS_LOCATION" , "LOCATION", "FLOOR_NUMBER" and "self".

推荐答案

您可以将 JToken 转换为 JObject,然后使用 Properties() 方法来获取对象属性的列表.从那里,您可以很容易地获得名称.

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

类似这样的:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

输出:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

这篇关于访问 JToken 中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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