Include class discriminators for polymorphic classes.

Sealed classes, abstract classes, and interfaces are polymorphic classes by definition. Open classes can be polymorphic if they are serializable with PolymorphicSerializer and properly registered in the SerializersModule. See kotlinx.serialization polymorphism guide for details.

Note that implementations of polymorphic classes (e.g., sealed class inheritors) are not polymorphic classes from kotlinx.serialization standpoint. This means that this mode adds class discriminators only if a statically known type of the property is a base class or interface.

In the example:

@Serializable class Plain(val p: String)
@Serializable sealed class Base
@Serializable object Impl: Base()

@Serializable class All(val p: Plain, val b: Base, val i: Impl)

setting JsonBuilder.classDiscriminatorMode to ClassDiscriminatorMode.POLYMORPHIC adds class discriminator to All.b, but leaves All.p and All.i intact.

See also


Link copied to clipboard
Link copied to clipboard