Hi here, I have a question on custom deserializers...
# serialization
b
Hi here, I have a question on custom deserializers. If I want to use the approach 2 from here, https://medium.com/transferwise-engineering/how-to-master-polymorphism-and-custom-serializers-in-kotlinx-serialization-7190da0f42aa to define a custom serializer on a data object, is there a way to still use the default deserializer for the class within the custom one? For the use case, we want to be able to use the default deserializer exactly as is and AFTER deserializing then set the json blob as a field on the class. (We need to do this to support phasing out existing deserializers while we're replacing the old classes with our new classes from a library)
I can use an external serializer, but then I'm unsure how to make sure that is used by default in cases where I have something like a list of the items I'm trying to deserialize
n
in the annotation you can specify what serializer it should use
@Serializable(with=Fruit.Companion::class)
but then i guess every .serializer() call on there will give you that and you effectively hides the original there is also parts of approach 1 that might be useful to you.. specifically
val serializersModule = SerializersModule { }
in there you can define what serializers to use for classes, mostly used for external classes.. but maybe this could allow you to use 2 serializers alongside each other
b
thank you! That led me to figuring out a solution that worked for me. I defined an external serializer, like so
Copy code
object EntitySerializer : KSerializer<Entity> {
    override fun deserialize(decoder: Decoder): Entity {
        val input = decoder as? JsonInput
            ?: throw SerializationException("Expected JsonInput for ${decoder::class}")
        val jsonObject = input.decodeJson() as? JsonObject
            ?: throw SerializationException("Expected JsonObject for ${input.decodeJson()::class}")
        val foo = decoder.json.parse(Entity.serializer(), jsonObject.toString())
        foo.originalJSON = jsonObject.toString()
        return foo
    }
}
and then used
Copy code
@file:UseSerializers(EntitySerializer::class)
in all the classes where I had lists of Entities and couldn't reference the EntitySerializer directly