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
Dominaezzz
11/13/2022, 2:41 PM
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
Shivam Verma
11/13/2022, 3:10 PM
Might you have an example somewhere for this kind of multi step serialization (even if the use-case is different)?
Shivam Verma
11/13/2022, 5:25 PM
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
Dominaezzz
11/13/2022, 5:31 PM
Instead of using the global JSON object, use the JSON object in the decoder.
decoder.json.decodeFromJsonElement
Dominaezzz
11/13/2022, 5:32 PM
Not sure about it IR exception but do create an issue for that.
s
Shivam Verma
11/13/2022, 5:57 PM
If anyone runs into this in future, here's a gist of my complete implementation along with tests. Thanks Dominic for all your help.