So while updating to 0.20, I had to make some chan...
# serialization
t
So while updating to 0.20, I had to make some changes to some customer serializers I had written, which highlighted the fact that I am unclear what the SerialDescriptor is actually used for, and how best to define it. So I would like those more knowledgeable to look at my code and tell me what I might be doing wrong, if anything (it currently appears to working fine [it is only used for input]). I am dealing with JSON that includes boolean values as true/false, “Y”/“N”, “0”/“1" or “true”/“false”. So I have the following:
Copy code
@Serializer(forClass = Boolean::class)
object BooleanSerializer: KSerializer<Boolean> {

    override val descriptor: SerialDescriptor = //StringDescriptor.withName("Format")
        PrimitiveDescriptor("BooleanSerializer", PrimitiveKind.BOOLEAN)

    override fun serialize(encoder: Encoder, obj: Boolean) {
        encoder.encodeInt(if (obj) 1 else 0)
    }

    override fun deserialize(decoder: Decoder): Boolean {
        val stringValue = decoder.decodeString()
        return stringValue == "Y" || stringValue == "1" || stringValue == "true"
    }
}
You can see the old definition for the descriptor of StringDescriptor, but I changed it to a PrimitiveDescriptor. I am still unclear what I should give as the serialName (does it include the package name, or just any name we want) and the PrimitiveKind (should this be a Boolean or a String in this case). Thank you to anyone who can edify me.
v
Thanks for posting. It is recommended to include package name to serial descriptor, so it won’t clash with anything else. Regarding
PrimitiveKind
— it is recommended to be a
<http://PrimitiveKind.INT|PrimitiveKind.INT>
, because you actually write an int and represent your boolean as a primitive int
t
Thank you for the response. I think I get it now. So I changed the descriptor to Boolean since I changed it to output only a boolean. It is really just to handle bad JSON coming in. I still want good JSON going out.
I do something similar for Doubles, since they can come in from our API as “3,435.32” (string and with a locale specific format).
If it can help others, here is the code. The Platform.parse() method is an expect which points to either an iOS (NSNumberFormatter) or Android (NumberFormat) implementation.