Accessing all items in the JToken

后端 未结 3 1107
[愿得一人]
[愿得一人] 2020-12-02 18:39

I have a json block like this:

{
    \"ADDRESS_MAP\":{

        \"ADDRESS_LOCATION\":{
            \"type\":\"separator\",
            \"name\":\"Address\",
         


        
3条回答
  •  一整个雨季
    2020-12-02 19:11

    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.

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    //Parse the data
    JObject my_obj = JsonConvert.DeserializeObject(your_json);
    
    foreach (KeyValuePair 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).

    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

提交回复
热议问题