Search code examples
kotlinjacksonmixinsjackson-databindjackson2

Mixin adding defaultImpl in Jackson does not work


I want to use Jackson mixin to provide a default implementation for an abstract type:

@JsonTypeInfo(
    use = Id.NAME,
    include = As.PROPERTY,
    property = "type",
    visible = true,
    defaultImpl = GenericRequest::class
)
@JsonMixin(Request::class)
class AlexaRequestMixin {
}

data class GenericRequest(
    val type: String, val requestId: String, val timestamp: OffsetDateTime
)

Base class that I want to alter with a mixin:

@JsonTypeInfo(
    use = Id.NAME,
    include = As.PROPERTY,
    property = "type",
    visible = true
)
@JsonSubTypes({@Type(
    value = InstallationError.class,
    name = "Alexa.DataStore.PackageManager.InstallationError"
), 
// ...
)})
public abstract class Request {

My objectMapper:

object mapper

However when I try to deserialize a class that is not present as subtype I get:

com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'Foo' as a subtype of 'com.amazon.ask.model.Request': known type ids = [...]


Solution

  • In order to make it work I had to:

    Make GenericRequest extend from the abstract Request class.

    When an abstract class is from Java and inheriting data class is from Kotlin it causes lots of problems.

    a) Data class cannot override same properties from abstract class https://youtrack.jetbrains.com/issue/KT-6653/Kotlin-properties-do-not-override-Java-style-getters-and-setters

    b) I had to change include = As.PROPERTY to include = JsonTypeInfo.As.WRAPPER_ARRAY

    So I ended up with implementing GenericRequest extending Request in Java...