I've got following classes :
public class City
public class Zoo
public abstract class Animal
abstract void eat();
I want to deserialize an instance of
City class with Jackson. Howerer, since
Animal is an abstract type, I've got following exception:
Could not read JSON: Can not construct instance of Animal, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
How to map
Animal to concrete type?
The problem is that I am able to modify only
Best How To :
For one-to-one (abstract/impl) use case, registering sub-classes (which you can do via
ObjectMapper.registerSubtypes(...), or using
SimpleModule) is an alternative to annotations.
But if you have truly polymorphic type,
@JsonTypeInfo annotation is the key. It needs to be added in the base class that is used static type (like
Animal), and will result in addition of a Type Identifier on serialization, and use of that id on deserialization. There are multiple choices both for kind of type id (class name vs logical name) as well as inclusion style (as property, as wrapper array, as wrapper object, as external property).