Add SubType information at runtime using Jackson for polymorphism
I ended up using Reflections library to find all subtype of Animal
class, and register JsonSubTypes with mapper.registerSubtypes(Class<?>... classes)
method.
Don't use @JsonSubTypes
. Use @JsonTypeInfo#use
with JsonTypeInfo.Id.CLASS
to identify types for serialization and deserialization.
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "type")
abstract class Animal { /* whatever */ }
Jackson will then store the fully qualified name to serialize the object and use it again to determine a target class for deserialization.
You'll have to make sure none of the subclasses have a property named type
.
It's possible to make this work with @JsonSubTypes
but it involves mixins and is not a very maintainable solution.