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