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".
So, you can iterate over it simply using a foreach : foreach (var x in obj) { string name = x. Key; JToken value = x. Value; … }
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.
JToken is the base class for all JSON elements. You should just use the Parse method for the type of element you expect to have in the string. If you don't know what it is, use JToken, and then you'll be able to down cast it to JObject, JArray, etc. In this case you always expect a JObject, so use that.
Parse() to parse a JSON string you know to represent an "atomic" value, requiring the use of JToken. Parse() in such a case. Similarly, JToken. FromObject() may be used to serialize any sort of c# object to a JToken hierarchy without needing to know in advance the resulting JSON type.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With