Is Jackson’s @JsonSubTypes still necessary for polymorphic deserialization?

There are two ways to achieve polymorphism in serialization and deserialization with Jackson. They are defined in Section 1. Usage in the link you posted.

Your code

    use = JsonTypeInfo.Id.MINIMAL_CLASS,
    include = JsonTypeInfo.As.PROPERTY,
    property = "@class")

is an example of the second approach. The first thing to note is that

All instances of annotated type and its subtypes use these settings
(unless overridden by another annotation)

So this config value propagates to all subtypes. Then, we need a type identifier that will map a Java type to a text value in the JSON string and vice versa. In your example, this is given by JsonTypeInfo.Id#MINIMAL_CLASS

Means that Java class name with minimal path is used as the type identifier.

So a minimal class name is generated from the target instance and written to the JSON content when serializing. Or a minimal class name is used to determine the target type for deserializing.

You could have also used JsonTypeInfo.Id#NAME which

Means that logical type name is used as type information; name will
then need to be separately resolved to actual concrete type (Class).

To provide such a logical type name, you use @JsonSubTypes

Annotation used with JsonTypeInfo to indicate sub types of
serializable polymorphic types, and to associate logical names used
within JSON content (which is more portable than using physical Java
class names).

This is just another way to achieve the same result. The documentation you’re asking about states

Type ids that are based on Java class name are fairly
straight-forward: it’s just class name, possibly some simple prefix
removal (for “minimal” variant). But type name is different: one has
to have mapping between logical name and actual class.

So the various JsonTypeInfo.Id values that deal with class names are straight-forward because they can be auto-generated. For type names, however, you need to give the mapping value explicitly.

Leave a Comment