The best way to serialize a class hierarchie

Hi everybody!

I have a question regarding class hierarchy: What is the right way to implement a class hierarchy here?

I have a class called Directory and a child class RootDirectory that has some additional properties.
I am aware of kotlinx.serialization/polymorphism.md at master · Kotlin/kotlinx.serialization · GitHub, but I did not understand how to implement it directly in this hierarchy.

So I implemented it the following way:

import kotlinx.serialization.Serializable
import kotlin.js.ExperimentalJsExport
import kotlin.js.JsExport

@Serializable
@JsExport
@ExperimentalJsExport
sealed class Directory {
    abstract val name: String
}

@Serializable
@JsExport
@ExperimentalJsExport
data class BasicDirectory(override val name: String) : Directory()

@Serializable
@JsExport
@ExperimentalJsExport
data class RootDirectory(override val name: String, val ancestor: String) : Directory()

// the corresponding Test: 
@Test
    fun SerializationWithSealedClass() {
        val ownedProject = RootDirectory("asdf", "root0")
        val json = Json.encodeToString(ownedProject)
        println(json)
        val decoded = Json.decodeFromString(RootDirectory.serializer(), json)
        println(decoded)
        val list = listOf(RootDirectory("asdf", "asdf"), BasicDirectory("asdf"), RootDirectoryV2("asdf", "root1", "space1"))
        val encodedList = Json.encodeToString(list)
        println(encodedList)
        val decodedList = Json.parseToJsonElement(encodedList)
        println(decodedList)
        val itemList = Json.decodeFromJsonElement<List<Directory>>(decodedList)
        println(itemList)
    }

Now the RootDirectory is still a Directory, but I need the additional sealed class Directory and BasicDirectory.
Now I have two questions:

  • Is there a more direct way of accomplishing the wanted thing?
  • In Kotlin/JS I get the following error:
{"name":"asdf","ancestor":"root0"}RootDirectory(name=asdf, ancestor=root0)
Serializer for class 'Directory' is not found.
Mark the class as @Serializable or provide the serializer explicitly.
On Kotlin/JS explicitly declared serializer should be used for interfaces and enums without @Serializable annotation
captureStack@/tmp/_karma_webpack_827286/commons.js:99378:25
SerializationException_init_$Create$_0@/tmp/_karma_webpack_827286/commons.js:108840:17
platformSpecificSerializerNotRegistered@/tmp/_karma_webpack_827286/commons.js:114278:11
serializer_0@/tmp/_karma_webpack_827286/commons.js:108889:46
builtinSerializer@/tmp/_karma_webpack_827286/commons.js:108944:31
serializerByKTypeImpl@/tmp/_karma_webpack_827286/commons.js:108924:13
serializer_0@/tmp/_karma_webpack_827286/commons.js:108886:47
...

What am I doing wrong here?

Thank you for your time!

Best Regards,
Johannes