Hi folks! Is there a way to deserialize a nullable...
# serialization
s
Hi folks! Is there a way to deserialize a nullable property to
null
if the deserialization fails (because the structure of the object changed). The closest approach I could find is this. However, this approach fails if the property changes to/from a primitive type.
d
Yes it is possible with multi step serialization. You'll have to write a custom serializer that first parses the structure to json, then attempts to deserialise the json into the target object. You can wrap the 2nd step in a try and catch.
s
Might you have an example somewhere for this kind of multi step serialization (even if the use-case is different)?
After some hit and trial, this is what worked for me. If I simply tried to return null, I could not get it to run and kept getting an exception with the IR. Would be helpful to know if I could somehow improve this further
Copy code
override fun deserialize(decoder: Decoder): AlphaProperty<T> {
    decoder as JsonDecoder
    val jsonElement: JsonElement = decoder.decodeJsonElement()

    return try {
        AlphaProperty.Known(Json.decodeFromJsonElement(valueSerializer, jsonElement))
    } catch (e: Exception) {
        AlphaProperty.Unknown
    }
}
d
Instead of using the global JSON object, use the JSON object in the decoder.
decoder.json.decodeFromJsonElement
Not sure about it IR exception but do create an issue for that.
s
If anyone runs into this in future, here's a gist of my complete implementation along with tests. Thanks Dominic for all your help.