Проблема полиморфной сериализации

@Serializable
abstract class Tutor {
    abstract val name: String
}
@Serializable
class Curator(
    override val name: String,
    val group: Group
) : Tutor()

val tutor:Tutor = Curator("Leader", Group("team", emptyList()))

Проблема полиморфной сериализации

println(Json.encodeToString(tutor))

  • Exception in thread “main” kotlinx.serialization.SerializationException: Class ‘Curator’ is not registered for polymorphic serialization in the scope of ‘Tutor’. Mark the base class as ‘sealed’ or register the serializer explicitly.

Ручная сериализация

println(
    Json.encodeToString(
        Curator.serializer(), 
        tutor as Curator
    )
)

Статическая полиморфная сериализация

@Serializable
sealed class Tutor {
    abstract val name: String
}
{
    "type":"Curator",
    "name":"Leader",
    "group":{"name":"team","students":[]}
}

Динамическая полиморфная сериализация

val tutorModule = SerializersModule {
    polymorphic(
        Tutor::class,           // baseClass
        Curator::class,         // actualClass
        Curator.serializer()    // actualSerializer
    )
}

println( Json { 
    serializersModule = tutorModule 
}.encodeToString(tutor))
{
    "type":"Curator",
    "name":"Leader",
    "group":{"name":"team","students":[]}
}