Option 1: Fixed Implementation
Following the assumption that you have access to the implementation of Base
, you can annotate it to always deserialize as the Sub
implementation using JsonDeserialize.as().
@JsonDeserialize(as = Sub.class)
class Base {
//etc.
}
Option 2: Content-based Implementation
Use a field to determine which implementation to deserialize as. See related answer for details: Deserializing polymorphic types with Jackson
Option 3: When Base
Isn't Accessible
This is a way to achieve behavior like option 1 and 2 without having access to the Base
class implementation. Assuming we want to achieve this with native Jackson, rather than a custom deserializer, we use Mix-ins. Mix-ins let you add annotations to a model you didn't define, by defining them on a matching signature in a different model.
To define the mix-in to produce Option 1 above:
@JsonDeserialize(as = Sub.class)
class BaseMixIn { }
And to use BaseMixIn, you must modify your ObjectMapper instance:
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Base.class, BaseMixIn.class);
Simply use the mapper
like any other ObjectMapper.