The Newtonsoft.json Nuget package allows you to serialize and deserialize objects into JSON.
In this article I will show you how to handle a scenario where your models are structured after interfaces and you need to implement them, but then you also need to know what the concrete type is to be able to deserialize your JSON.
Some basic operations from Newtonsoft.Json are:
You can convert an object to JSON using:
- JsonConvert.SerializeObject(main);
And convert it back using:
- YourType x = JsonConvert.DeserializeObject<YourType>(json);
It also supports dynamic objects:
- dynamic dyn = JsonConvert.DeserializeObject(json);
-
These methods work just fine for concrete types. However if you have an interface in the middle you will get errors. For example, given the following structure:
- public interface IMainStuff
- {
- ISubStuff SubStuff { get; set; }
- }
- public interface ISubStuff
- {
- string Name { get; set; }
- }
-
- public class MainStuff : IMainStuff
- {
- public ISubStuff SubStuff { get; set; }
- }
-
- public class SubStuff : ISubStuff
- {
- public string Name { get; set; }
- }
If you attempt to deserialize MainStuff you will get the following exception:
- An unhandled exception of type "Newtonsoft.Json.JsonSerializationException" occurred in Newtonsoft.Json.dll.
- Additional information: Could not create an instance of type ConsoleApplication1.Program+ISubStuff. Type is an interface or abstract class and cannot be instantiated. Path "SubStuff.Name", line 1, position 20.
Json.NET does not know how to create the interface. If you want to handle it you need to implement a converter as in the following:
- public class ConcreteConverter<T> : JsonConverter
- {
- public override bool CanConvert(Type objectType) => true;
-
- public override object ReadJson(JsonReader reader,
- Type objectType, object existingValue, JsonSerializer serializer)
- {
- return serializer.Deserialize<T>(reader);
- }
-
- public override void WriteJson(JsonWriter writer,
- object value, JsonSerializer serializer)
- {
- serializer.Serialize(writer, value);
- }
- }
And then tell your concrete class how to handle the interface property by annotating it with the converter information.
- public class MainStuff : IMainStuff
- {
- [JsonConverter(typeof(ConcreteConverter<SubStuff>))]
- public ISubStuff SubStuff { get; set; }
- }