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!
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:
You can call the method as shown below.
obj
will either contain aDictionary<string, object>
,List<object>
, or primitive depending on what JSON you started with.I love AutoMapper and seem to think it solves many problems... like this one...
why not just let the JSON.NET convert the thing into whatever it wants to... and use AutoMapper to map it into the object you really want.
Unless performance is paramount this extra step should be worth it for the reduction in complexity and the ability to use the serializer you want.
One way to deserialize a json string recursively into dictionaries and lists with JSON.NET is to create a custom json converter class that derives from the
JsonConverter
abstract class provided by JSON.NET.It is in your derived
JsonConverter
where you put the implementation of how an object should be written to and from json.You can use your custom
JsonConverter
like this:Here is a custom JsonConverter I have used with success in the past to achieve the same goals as you outline in your question:
Here is the equivalent in
f#
:You can have full control over the serialization of a type by using a custom
JsonConverter
. Documentation at http://james.newtonking.com/projects/json/help/html/T_Newtonsoft_Json_JsonConverter.htm .Also, according to this blog post you need to use
JArray
for a List, andJObject
for a dictionary.You cannot do what I was asking. At least not as far as I can tell after MUCH research. I had to edit the source of Json.NET.