I've been trying to write a "SafeSerializer", a cu...
# serialization
j
I've been trying to write a "SafeSerializer", a custom serializer that allows me to return null when the serialization of an object fails, however I feel my knowledge of serialization is lacking and I can't seem to get it to work. Has anyone done something similar, or has any idea how it would look?
This is one of the iterations I currently have
Copy code
open class FallbackSerializer<T>(
    private val serializer: KSerializer<T>,
) : KSerializer<T?> {
    override val descriptor: SerialDescriptor = serializer.descriptor

    override fun serialize(
        encoder: Encoder,
        value: T?,
    ) {
        if (value != null) {
            try {
                serializer.serialize(encoder, value)
            } catch (e: SerializationException) {
               
            }
        }
    }

    override fun deserialize(decoder: Decoder): T? =
        try {
            serializer.deserialize(decoder)
        } catch (e: SerializationException) {
            null
        }
}
However it doesn't seem to work right, and I need to instantiate a new object for each type I wish to apply it to, rather than a generic one I can use with
with=
This one for example errors out on
Copy code
Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method app.FallbackSerializer.<init>, parameter serializer
e
AFAICS this is impossible in general. an exception in the serializer may leave the encoder in an unknown state
j
Can you elaborate on that a little?