.net - How do I use JSON.NET to deserialize into nested/recursive Dictionary and List? -
i need deserialize complex json blob standard .net containers use in code not aware of json. expects things in standard .net types, dictionary[string, object] or list[object] "object" can primitive or recurse (dictionary or list).
i cannot use static type map results , jobject/jtoken don't fit. ideally, there way (via contracts perhaps?) convert raw json basic .net containers.
i've search on way coax json.net deserializer creating these simple types when encounters "{}" or "[]" little success.
any appreciated!
if want generic method can handle arbitrary json , convert nested structure of regular .net types (primitives, lists , dictionaries), can use json.net's linq-to-json api it:
using system.linq; using newtonsoft.json.linq; public static class jsonhelper { public static object deserialize(string json) { return toobject(jtoken.parse(json)); } private static object toobject(jtoken token) { switch (token.type) { case jtokentype.object: return token.children<jproperty>() .todictionary(prop => prop.name, prop => toobject(prop.value)); case jtokentype.array: return token.select(toobject).tolist(); default: return ((jvalue)token).value; } } } you can call method shown below. obj either contain dictionary<string, object>, list<object>, or primitive depending on json started with.
object obj = jsonhelper.deserialize(jsonstring);
Comments
Post a Comment