List of abstract objects and json
I recently bumped into an issue where we would had a list of abstract objects that we needed to be able to serialize it and then deserialize it back. Further more, it needed to without special serializer settings or other configuration heavy solutions, since we are providing a model library to third parties and they should be able to deserialize our data without problems.
Given the following types
A list of List<ItemType>
the serialized JSON will look something like this
But when we try to deserialize json.net will return the following error: >Could not create an instance of type ListItem. Type is an interface or abstract class and cannot be instantiated.` Which make perfect sense since there is no way JsonNet is able to tell the difference between the different types.
Json.Net supports adding type names to the serialized data using the setting TypeNameHandling = TypeNameHandling.All
, but it messes up the data quite a lot.
I really don’t like this, especially not when I might also have non .Net clients.
The solution was to make a special list with a JsonConverter attribute to instruct Json.Net to add the type name to the data and how to deserialise it again.
With a list like this:
And then the Json looks like this:
I really like this solution as we are not polluting our data, and not requiring our clients to do anything special to consume the data.