Skip to content
Advertisement

Jackson deserialization to concrete polymorphic class

I have following Jackson annotated classes (Kotlin)

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.PROPERTY,
    property = "type"
)
@JsonSubTypes(
    value = [
        JsonSubTypes.Type(value = Child1::class, name = "child1"),
        JsonSubTypes.Type(value = Child2::class, name = "child2")
    ]
)
sealed class Parent 

class Child1: Parent()
class Child2: Parent()

I try to deserialize JSON that does not contain type property but I provide concrete class so it should not matter

// Kotlin extension method provides type in runtime
mapper.readValue<Child1>(json)

I get Missing type id when trying to resolve subtype of ... anyway. Is there a way how to tell Jackson to use the type provided in the deserialization and not to try find it from the type property?

Advertisement

Answer

There’s a default implementation class to use for deserialization via defaultImpl:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = Child1.class)

From the Javadoc:

Optional property that can be used to specify default implementation class to use for deserialization if type identifier is either not present, or can not be mapped to a registered type (which can occur for ids, but not when specifying explicit class to use). Property has no effect on choice of type id used for serialization; it is only used in deciding what to do for otherwise unmappable cases.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement