I have no issue deserializing JSON into known types or into Dictionary objects, but what about cases where I don't know what the input is going to be? Specifically I'm referring to receiving a JSON string that represents a flat or nested set of key-value pairs:
{
foo: 'bar',
baz: 42
}
or
{
foo:
{
bar: 42,
baz: ['foo', 'bar', 'baz']
}
}
But what about cases where the input isn't a key-value-pair, but rather an array, or, an array of objects with other nested objects (including arrays)?
[
{ foo: 'bar', baz: [ 1, 2, 3 ] },
{ foo: 'baz', bar: [ 4, 5, 6 ] }
]
My goal is to have a single class that I could deserialize any of the above into, and then iterate each of its members. The input could be of any structure, so I can't assume the data will come in matching any type I've already defined.
I haven't been able to find a way to do this. Anyone have any guidance?
Edit:
Seems easy enough to JToken.Parse the JSON string; a helpful next step would be to iterate its members and handle JArray and JObject separately.
JToken token = JToken.Parse(json)
. Or if you prefer plain old .Net objects, see How do I use JSON.NET to deserialize into nested/recursive Dictionary and List? – Brian Rogers