Deserializing interfaces with Json.NET

Using Json.NET with concrete types is very simple: Just give your object to JsonConvert.Serialize() and give your string to JsonConvert.Deserialize() to get back an instance. Wonderfully simple and convenient.

When you are working with your objects as interfaces, things are only a little more complex during deserialization. With simple objects can simply point the JsonConvert.Deserialize() method to an implementation of your interface. Otherwise, the framework does not have a concrete class to instantiate.

You can just call JsonConvert.Deserialize() to deserialize one of these.

However, what if there are multiple implementation types involved?

You need to tell JsonConvert about your implementation of IMyTransferType as well as the IMyInnerType, but JsonConvert.Deserialize only allows you to specify the parent-most type. To accomplish this, you just need to write simple custom converters. Simply create one class for each of your interface types, inherit from CustomConverter, and have its Create method return a new instance of an implementation:

Use a JsonSerializerSettings class with these classes added to its Converters collection when invoking the JsonConvert.Deserialize method:

Now, JsonConvert will know how to deserialize the child objects as well as the parent-most object.