Császár Ákos
06/26/2024, 2:52 PM@Serializable(with = BaseSerializer::class)
interface Base {
val objectType: String?
}
@Serializable
class FinalA : Base {
override val objectType: String? = null
val valueA: String? = null
}
@Serializable
class FinalB : Base {
override val objectType: String? = null
val valueB: Int? = null
}
class BaseSerializer : KSerializer<Base> {
override val descriptor: SerialDescriptor = buildClassSerialDescriptor("BaseAssetDescriptor") {
element<String>("objectType", isOptional = true)
}
override fun deserialize(decoder: Decoder): Base {
return decoder.decodeStructure(descriptor) {
val type = decodeStringElement(descriptor, 0) // should be "A" or "B" but its "objectType"
when (type) {
"A" -> FinalA.serializer().deserialize(decoder)
"B" -> FinalB.serializer().deserialize(decoder)
else -> throw Exception("Wrong polymorphic type $type")
}
}
}
override fun serialize(encoder: Encoder, value: Base) {
when (value) {
is FinalA -> FinalA.serializer().serialize(encoder, value)
is FinalB -> FinalB.serializer().serialize(encoder, value)
}
}
}
At deserialization, the type always will be "objectType" instead of "A" for the following input: {"objectType": "A", "valueA":"asd"}
How should I properly deserialize it?