4

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:

  1. Is this is the correct approach to fix this issue (And not sure what this option is not out of box)

  2. Any performance or negative impacts that I should be aware of with this setting.

Thanks.

Jim Hewitt
  • 1,726
  • 4
  • 24
  • 26
Nil Pun
  • 17,035
  • 39
  • 172
  • 294
  • 1
    When using `TypeNameHandling` you need to validate the incoming types with a custom serialization binder, for security reasons. See e.g. [TypeNameHandling caution in Newtonsoft Json](http://stackoverflow.com/q/39565954/3744182) for why. For an alternative strategy see [Deserializing polymorphic json classes without type information using json.net](http://stackoverflow.com/q/19307752/3744182). – dbc Jan 23 '17 at 03:28
  • 1
    @dbc [This link](http://stackoverflow.com/questions/29124126/polymorphic-json-deserialization-failing-using-json-net) is better because it fixes a bug in your second link if the json object is recursive. – Cheng Chen Jan 23 '17 at 03:38

1 Answers1

3

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

Trung Duong
  • 3,475
  • 2
  • 8
  • 9