I have service that will receive some data in ‘json’, i don’t know which data. However I have set of attributes that might be there.
the Json format is something like this and can’t be changed, names could be different:
{"Parent1":
{"Child1":"Value1","Child2":"Value2"},
"Parent2":
{"Child1":"Value1","Child2":"Value2"},
"Parent3":
{"Child1":
{"SubChild1":"Value1","SubChild2":"Value2"}}
}
I want to enumerate through all items to be able get key:value pairs.
Please note that hierarchy is important as several objects could have the same key but different parent.
Also please note that I don’t know keys, i need to get keys as well as values, so I can’t get a POCO object out of this straight away.
So the question basically is: how to get a collection that would implement some iterator through all the properties (with accessor to both key and value) and would support hierarchy.
You can always deserialize the JSON input into some (untyped) DOM where you can traverse the tree which represents the JSON document. There are a couple of options: the JavaScriptSerializer class, which will deserialize that JSON into a
Dictionary<string, object>(for arrays it would deserialize into anobject[]). Or you can use a third-party library, such as JSON.NET, which you can deserialize arbitrary JSON into a JToken/JObject/JArray/JValue tree, and traverse it using the methods from those classes.