The Newtonsoft.json Nuget package allows you to serialize and deserialize objects into JSON.
Install-Package Newtonsoft.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);
- YourType x = JsonConvert.DeserializeObject<YourType>(json);
- dynamic dyn = JsonConvert.DeserializeObject(json);
- // dyn.Stuff
- 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);
- }
- }
- public class MainStuff : IMainStuff
- {
- [JsonConverter(typeof(ConcreteConverter<SubStuff>))]
- public ISubStuff SubStuff { get; set; }
- }


Amogh NatuPosted Feb 11, 2021, 9:34 PM
Thank you for the article. This definitely helped me!
NAGENDRA BONAMPosted Jun 1, 2020, 9:24 PM
It is not working for the IList<ISubStuff> substuff {get; set}. Throwing Error setting value to substuff on MainStuff.
Tarun SharmaPosted May 3, 2019, 2:33 PM
How can we do this if you multiple classes implementing ISubStuff
Sonu ChaudharyPosted Feb 25, 2016, 7:15 AM
nice article
Ricky NguyenPosted Sep 25, 2015, 6:16 AM
Nice one, and thanks.
Mahipatsinh MoriPosted Sep 1, 2015, 8:05 AM
Great !
Sibeesh VenuPosted Jun 1, 2015, 1:42 AM
Good one.
Santhakumar MunuswamyPosted May 31, 2015, 11:15 PM
Thanks for nice one
Atul GuptaPosted May 31, 2015, 6:47 AM
Good One!