Skip to content

Auto-detect sealed classes (similar to @JsonSubTypes)Β #239

@shartte

Description

@shartte

I am not sure whether this is actually possible given Jacksons API, but I'd like to avoid having to specify the @JsonSubTypes annotation when working with polymorphic sealed classes.

Here's an example that'll work with the current module:


@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes(
        JsonSubTypes.Type(Either.A::class, name = "a"),
        JsonSubTypes.Type(Either.B::class, name = "b")
)
sealed class Either {

    data class A(var field: String = "") : Either()

    data class B(var otherField: String = "") : Either()

}

But here's how I'd like it to look:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
sealed class Either {

    @JsonTypeName("a")
    data class A(var field: String = "") : Either()

    @JsonTypeName("b")
    data class B(var otherField: String = "") : Either()

}

This should be possible given that Kotlin exposes the sealed class's subclasses as Either::class.sealedSubclasses.

And here's a test function:

fun main() {

    val mapper = ObjectMapper()
    val either = mapper.readValue<Array<Either>>("""[
        {
            "@type": "a",
            "field": "value"
        },
        {
            "@type": "b",
            "otherField": "1234"
        }
    ]""")
    println(either.contentToString())

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions