I've a concrete class below which inherits from abstract class:
[Serializable]
public class MyConcreteClass : MyAbstractClass
{
public string MyProperty { get; set; }
}
[Serializable]
public abstract class MyAbstractClass { }
NewtonSoft JSON Serializer throws exception below when trying to de/serialize MyconcreteClass class:
Newtonsoft.Json.JsonSerializationException: Could not create an instance of type MyAbstractClass. Type is an interface or abstract class and cannot be instantiated. Path ....
Did a bit of googling and found this setting below:
var settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
};
If I use above setting i.e. TypeNameHandling.All, the error goes away.
Questions in my mind:
Is this is the correct approach to fix this issue (And not sure what this option is not out of box)
Any performance or negative impacts that I should be aware of with this setting.
Thanks.
1. Is this is the correct approach to fix this issue (And not sure what this option is not out of box)
I think it's correct approach to to de/serialize inheritance class with NewtonSoft JSON. When we de/serialize with setting TypeNameHandling = TypeNameHandling.All, the .NET type name will always be included when serializing. Without the type information, it's hard for converter to decide which class will be de/serialized.
2. Any performance or negative impacts that I should be aware of with this setting.
As remarked in Json.NET Documentation, TypeNameHandling should be used with caution when your application deserializes JSON from an external source and you should create a custom SerializationBinder when deserializing with a value other than TypeNameHandling.None.
You could reference the following links
http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm
https://mallibone.com/post/serialize-object-inheritance-with-json.net
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With