Hi, i don't really get SerialDescriptor things. I ...
# serialization
Hi, i don't really get SerialDescriptor things. I would be grateful if someone could code review my code below and tell me if i do something terribly wrong. My problem is that abstract objects are boxed inside of object which contains information about their type. But after deserialization i do not want to always unbox my object manually. I feel like I should use
but i not sure if it was intended for such cases. Current working code below:
Copy code
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.Serializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.encoding.decodeStructure
import kotlinx.serialization.json.Json
import org.junit.Assert
import org.junit.Test

class WSampleTest {
    val parser = Json {
        isLenient = true
        ignoreUnknownKeys = true
        allowSpecialFloatingPointValues = true
        useArrayPolymorphism = false

    fun shouldParseFirst() {
        val string = """{"type":"first", "data":{"name":"test"}}"""
        val firstObj = parser.decodeFromString(CustomClassObjSerializer, string)
        Assert.assertEquals(CustomClassSpecificFirst("test"), firstObj)

    fun shouldParseSecond() {
        val string = """{"type":"second", "data":{"otherName":"otherTest"}}"""
        val firstObj = parser.decodeFromString(CustomClassObjSerializer, string)
        Assert.assertEquals(CustomClassSpecificSecond("otherTest"), firstObj)

@Serializer(forClass = CustomClassObj::class)
object CustomClassObjSerializer : KSerializer<CustomClassObj> {

    override val descriptor: SerialDescriptor = CustomClassBoxWithType.serializer().descriptor

    override fun deserialize(decoder: Decoder): CustomClassObj {
        decoder.decodeStructure(descriptor) {
            val serializer = when (decodeStringElement(descriptor, 0)) {
                "first" -> CustomClassSpecificFirst.serializer()
                "second" -> CustomClassSpecificSecond.serializer()
                else -> UnknownMessage.serializer()
            return decodeSerializableElement(

    override fun serialize(encoder: Encoder, value: CustomClassObj) =
        throw IllegalStateException("serialize is not supported")

data class CustomClassBoxWithType(val type: String, val data: CustomClassObj)

abstract class CustomClassObj

data class CustomClassSpecificFirst(val name: String) : CustomClassObj()

data class CustomClassSpecificSecond(val otherName: String) : CustomClassObj()

object UnknownMessage : CustomClassObj()