kotlinx.serialization
kotlinx.serialization copied to clipboard
Deserialize sealed class with generic
Is there are any way for deserialize classes like below? Tested in kotlin native
@Serializable
sealed class Foo<T> {
abstract val value: T
@Serializable
data class BarInt(override val value: Int) : Foo<Int>()
@Serializable
data class BarFloat(override val value: Float) : Foo<Float>()
}
@Test
fun someFun() {
val barInt: Foo<Int> = Foo.BarInt(42)
val json = json().encodeToString(barInt)
logError { "json: $json" }
val decodedBarInt: Foo<*> = json().decodeFromString(json) <-- crashes here with message "Star projections in type arguments are not allowed, but had network.Foo<*> (Kotlin reflection is not available)"
logError { "decodedBarInt: $decodedBarInt" }
}
serialized json string:
json: {
"type": "network.Foo.BarInt",
"value": 42
}
Not yet but do you really need generics here? Especially since you end up doing Foo<*>.
What's wrong with this?
@Serializable
sealed class Foo {
abstract val value: Any
@Serializable
data class BarInt(override val value: Int) : Foo()
@Serializable
data class BarFloat(override val value: Float) : Foo()
}
Thanks for response! In my case i need something like this:
@Serializable
sealed class Foo<T> {
abstract val x: T
abstract val y: T
@Serializable
data class BarInt(
override val x: Int,
override val y: Int
) : Foo<Int>()
@Serializable
data class BarFloat(
override val x: Float,
override val y: Float
) : Foo<Float>()
}
I need to describe two values with same type for certain data class
Workaround: use Json.decodeFromString(Foo.serializer(PolymorphicSerializer(Any::class)), json)