Husein Behboodi Rad Husein Behboodi Rad - 4 months ago 28
JSON Question

accessing all items in the JTOKEN, json.net

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


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

Thanks

Answer

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.

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