Hi all! Maybe a bit similar to the previous post, ...
# serialization
a
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:
Copy 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
t
I guess it's because animalType isn't actually a field. It's polymorphic property and Dog class implements it to always return "Dog"
a
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
i
change
val rex = Dog("")
to
val rex: Animal = Dog("")
And you probably don't need the
Dog.serializer
just
Json.encodeToString(rex)
t
You can use: kotlinx.serialization.SerialName with custom polymorphic serializer (to change the name of "type" serial name)
Copy code
@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"
    }
}
a
@Antoine Gagnon You have to add
@Required
to
animalType
field. Without this marker
serialization
doesn’t write into json field with default value.
a
Thanks @aleksey.tomin, that’s exactly what I was looking for!