Kotlin sealed interface serialization seems to be broken, unless using an explicitly registered serialization module. Am I missing something?
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlin.test.Test
sealed interface iFoo {
@Serializable
@SerialName("a")
class A() : iFoo//Foo(),
}
class EventTest {
@Test
fun testKotlinLang() {
// // this works
// val json = Json { serializersModule = SerializersModule {
// polymorphic(iFoo::class) {
// subclass(iFoo.A::class, iFoo.A.serializer())
// } } }
val json = Json
val a = iFoo.A() as iFoo
val s = json.encodeToString(a)
val a1: iFoo = json.decodeFromString(s)
}
}
Class 'A' is not registered for polymorphic serialization in the scope of 'iFoo'.
Mark the base class as 'sealed' or register the serializer explicitly.
kotlinx.serialization.SerializationException: Class 'A' is not registered for polymorphic serialization in the scope of 'iFoo'.
Mark the base class as 'sealed' or register the serializer explicitly.
at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:102)
at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:113)
at kotlinx.serialization.PolymorphicSerializerKt.findPolymorphicSerializer(PolymorphicSerializer.kt:109)
at kotlinx.serialization.json.internal.StreamingJsonEncoder.encodeSerializableValue(StreamingJsonEncoder.kt:224)
at kotlinx.serialization.json.Json.encodeToString(Json.kt:85)
at io.almer.EventTest.testKotlinLang(EventTest.kt:64)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
..............
Note that I am using the multiplatform mode but the JVM run fails.
CodePudding user response:
Apparently it's not implemented yet :(
https://github.com/Kotlin/kotlinx.serialization/issues/1417
CodePudding user response:
Possible work-around using sealed interface
with @JvmInline
: https://github.com/Kotlin/kotlinx.serialization/issues/1417#issuecomment-844300565