I need to deserialize a complex JSON blob into standard .NET containers for use in code that is not aware of JSON. It expects things to be in standard .NET types, specifically Dictionary<string, object>
or List<object>
where "object" can be primitive or recurse (Dictionary or List).
I cannot use a static type to map the results and JObject/JToken don't fit. Ideally, there would be some way (via Contracts perhaps?) to convert raw JSON into basic .NET containers.
I've search all over for any way to coax the JSON.NET deserializer into creating these simple types when it encounters "{}" or "[]" but with little success.
Any help appreciated!
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Newtonsoft. Json uses reflection to get constructor parameters and then tries to find closest match by name of these constructor parameters to object's properties. It also checks type of property and parameters to match. If there is no match found, then default value will be passed to this parameterized constructor.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.
Simple One-Line Answer. This code will convert any Dictionary<Key,Value> to Dictionary<string,string> and then serialize it as a JSON string: var json = new JavaScriptSerializer(). Serialize(yourDictionary.
If you just want a generic method that can handle any arbitrary JSON and convert it into a nested structure of regular .NET types (primitives, Lists and Dictionaries), you can use JSON.Net's LINQ-to-JSON API to do it:
using System.Linq; using Newtonsoft.Json.Linq; public static class JsonHelper { public static object Deserialize(string json) { return ToObject(JToken.Parse(json)); } public 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 the method as shown below. obj
will either contain a Dictionary<string, object>
, List<object>
, or primitive depending on what JSON you started with.
object obj = JsonHelper.Deserialize(jsonString);
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