C# 访问 JToken 中的所有项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16795045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:47:07  来源:igfitidea点击:

Accessing all items in the JToken

c#jsonjson.net

提问by Husein Behboodi Rad

I have a json block like this:

我有一个像这样的 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"
        }
    }
}

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".

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

采纳答案by Brian Rogers

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

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

Something like this:

像这样的东西:

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);
}

Output:

输出:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

回答by James Sinclair

If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.

如果您知道您收到的 json 的结构,那么我建议您拥有一个反映您在 json 中收到的内容的类结构。

Then you can call its something like this...

然后你可以这样称呼它......

AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);

(Where json is a string containing the json in question)

(其中 json 是包含相关 json 的字符串)

If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.

如果您不知道您收到的 json 的格式,那么它会变得更复杂一些,您可能需要手动解析它。

check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspxfor more info

查看http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx了解更多信息

回答by Ian

In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.

除了已接受的答案,我还想给出一个答案,说明如何直接迭代 Newtonsoft 集合。它使用更少的代码,我猜它更有效,因为它不涉及转换集合。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);

foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
    Console.WriteLine(sub_obj.Key);
}

I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).

我自己开始这样做是因为 JsonConvert 会自动将嵌套对象反序列化为 JToken(我认为下面是 JObject、JValue 或 JArray)。

I think the parsing works according to the following principles:

我认为解析根据以下原则进行:

  • Every object is abstracted as a JToken

  • Cast to JObject where you expect a Dictionary

  • Cast to JValue if the JToken represents a terminal node and is a value

  • Cast to JArray if its an array

  • JValue.Value gives you the .NET type you need

  • 每个对象都被抽象为一个 JToken

  • 投射到您期望字典的 JObject

  • 如果 JToken 代表终端节点并且是一个值,则转换为 JValue

  • 如果它是一个数组,则转换为 JArray

  • JValue.Value 为您提供所需的 .NET 类型