David Le Bouquin
Nov 5 · 1 min read

Since jackson-module-kotlin ≥ 2.10.0 you can do:

The class to serialize:

sealed class SubjectId {
data class ProductId(val id: String) : SubjectId()
data class BannerId(val id: Int) : SubjectId()
}

The mixin:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
sealed class SubjectIdMixin {
@JsonTypeName("product_id")
data class ProductId(val id: String) : SubjectIdMixin()

@JsonTypeName("banner_id")
data class BannerId(val id: Int) : SubjectIdMixin()
}

Finally link the two:

mapper.addMixIn(SubjectId::class.java, SubjectIdMixin::class.java)

You can also annotate directly the classes to serialize without using a mixin.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade