Antoine Gagnon

    Antoine Gagnon

    1 year ago
    Hi all! Maybe a bit similar to the previous post, but I’m having issues understanding why the
    animalType
    field isn’t serialized in my code:
    @Serializable
    abstract class Animal{
        abstract val name : String
        abstract val animalType : String
    }
    
    @Serializable
    class Dog(override val name:String):Animal(){
        override val animalType: String = "Dog"
    }
    
    val rex = Dog("Rex")
    val string = Json.encodeToString(Dog.serializer(),rex)
    println(string)
    The
    string
    value at the end is always
    {"name":"Rex"}
    and doesn’t include the
    animalType
    field
    Tomasz Krakowiak

    Tomasz Krakowiak

    1 year ago
    I guess it's because animalType isn't actually a field. It's polymorphic property and Dog class implements it to always return "Dog"
    Antoine Gagnon

    Antoine Gagnon

    1 year ago
    My end goal is to use it to pick which serializer to use when serializing/deserializing an
    Animal
    since it’ll be a different discriminator that the default one
    Igor Brishkoski

    Igor Brishkoski

    1 year ago
    change
    val rex = Dog("")
    to
    val rex: Animal = Dog("")
    And you probably don't need the
    Dog.serializer
    just
    Json.encodeToString(rex)
    Tomasz Krakowiak

    Tomasz Krakowiak

    1 year ago
    You can use: kotlinx.serialization.SerialName with custom polymorphic serializer (to change the name of "type" serial name)
    @OptIn(ExperimentalSerializationApi::class)
    public class AnimalSerializer<T : Any> : AbstractPolymorphicSerializer<T>() {
        public override val descriptor: SerialDescriptor =
            buildSerialDescriptor("kotlinx.serialization.Polymorphic", PolymorphicKind.OPEN) {
                element("animalType", String.serializer().descriptor)
                element(
                    "value",
                    buildSerialDescriptor("kotlinx.serialization.Polymorphic<${Animal::class.simpleName}>", SerialKind.CONTEXTUAL)
                )
            }.withContext(Animal::class)
    
        override fun toString(): String {
            return "kotlinx.serialization.AnimalSerializer"
        }
    }
    Igor Brishkoski

    Igor Brishkoski

    1 year ago
    aleksey.tomin

    aleksey.tomin

    1 year ago
    @Antoine Gagnon You have to add
    @Required
    to
    animalType
    field. Without this marker
    serialization
    doesn’t write into json field with default value.
    Antoine Gagnon

    Antoine Gagnon

    1 year ago
    Thanks @aleksey.tomin, that’s exactly what I was looking for!