In cases where polymorphic types are persisted to JSON, there’s no way for Jackson to figure out the right type during deserialization. Let’s understand that with an example.
This annotation is used to serialize information about actual class of polymorphic instances, so that Jackson can know what subtype is to be deserialized. Let’s fix about exception by using this annotation:
Above configuration specifies that the qualified class name should be used (use = JsonTypeInfo.Id.CLASS) and persist that as JSON property (include = JsonTypeInfo.As.PROPERTY). The property name should be ‘className’. Let’s run our main method again:
In above configuration if we skip optional elements, ‘include’ and ‘property’, then defaults will be used. The default ‘include’ is also JsonTypeInfo.As.PROPERTY and default ‘property’ is @class. So our example will be:
If this annotation exists on both class and property, then the one on property has precedence, as it is considered more specific.
When used on properties (fields, methods), this annotation applies to values. That means when used on collection types (Collection, Map, arrays) it will apply to the elements, not the collection itself. For non-collection types there is no difference. In above snippet when we used it on ‘shapes’ list, it is applied on each element (Shape) of the List rather than List type itself.
Using JsonTypeInfo.Id.MINIMAL_CLASS
use = JsonTypeInfo.Id.MINIMAL_CLASS option will serialize minimal relative package path. Check out complete example here.
Using ObjectMapper.enableDefaultTyping()
This method can be used to enable global automatic inclusion of type information in cases where polymorphic types are used.
In above example DefaultTyping.OBJECT_AND_NON_CONCRETE specifies that default typing will be used for properties with declared type of java.lang.Object or an abstract type (abstract class or interface, Shape in our example).
Note that in above output the actual type of List is also persisted as ArrayList. That’s because List is also a non-concrete type.
Example Project
Dependencies and Technologies Used:
ackson-databind 2.9.6: General data-binding functionality for Jackson: works on core streaming API.