Hi! I am trying to write a custom polymorphic seri...
# serialization
c
Hi! I am trying to write a custom polymorphic serializer that supports both Json and Cbor, but I am not sure how to do it.
Copy code
@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?