This article shows how to deserialize JSON into a collection of objects of dynamic types with JSON.NET
It is often asked by those just starting to use JSON.NET - how to deserialize a collection of objects for which we only know the base type, while the actual type needs to be determined during the transformation, based on JSON data?
It is quite a fundamental question about JSON.NET, which I intend to answer here in the most simplistic way.
Let's consider two typical JSON examples you are likely to encounter:
- Deserializing a JSON array into type
- Deserializing JSON list of objects into type
We start with declaration of the classes that expect the data:
public class TestBase
public class TestA : TestBase
public string text;
public class TestB : TestBase
public DateTime date;
For a list of type
List<TestBase> you may use JSON like shown below:
And for a dictionary of type
Dictionary<int, TestBase> you might use JSON as follows:
In both JSON examples we added attribute
Using the code
type to tell us which object type can contain the data. And we just need a way to pass it on to JSON deserializer for correct type instantiation. The following chapter explains how to do that.
We assume here that you already have a project where you are using JSON.NET, because if not, this tip isn't for you at all.
In order to convert JSON into the aforementioned
Dictionary types, use code as shown below:
JsonVirtualConverter<TestBase> jvc = new JsonVirtualConverter<TestBase>("type", t =>
return new TestA();
return new TestB();
string list = File.ReadAllText("../../JSON/ListData.json");
string dict = File.ReadAllText("../../JSON/DictData.json");
List<TestBase> a = JsonConvert.DeserializeObject<List<TestBase>>(list, jvc);
Dictionary<int, TestBase> b = JsonConvert.DeserializeObject<Dictionary<int, TestBase>>(dict, jvc);
Above we set up our instantiation object to create the right type of objects based on attribute
type, and then let JSON.NET take care of the rest.
For both transformations we passed an instance of
JsonVirtualConverter, which is a very simple class attached to this article, created just to solve the exact problem this article describes.
Points of Interest
Currently, playing with advanced JSON stuff as part of a web project.
Also, by publishing this tip I'm trying to get some attention from the author of JSON.NET, James Newton-King, to convince him to include this simple class JsonVirtualConverter into the next release of JSON.NET. He seems to be very hard to reach
- August 04, 2013 - Initial Draft