kotlinx.serialization icon indicating copy to clipboard operation
kotlinx.serialization copied to clipboard

Support nullable types in JsonTransformingSerializer

Open marcosalis opened this issue 3 years ago • 0 comments

What is your use-case and why do you need this feature? Based on this comment, a custom JsonTransformingSerializer doesn't support nullable types.

There is currently no straightforward way (except cumbersome usage of null "marker objects" in data) to handle custom deserialization of a null JSON field when one needs to directly read from a JsonElements to create a decoded model.

A pretty common use case would be setting a property to null or to a default type in a model when an unexpected value (or set of values) is encountered while reading the JSON element in a legacy API.

Describe the solution you'd like As suggested in the comment above, it would be enough for JsonTransformingSerializer to support nullable types:

object ModelSerializer : JsonTransformingSerializer<Model?>(Model.serializer().nullable) {

    override fun transformDeserialize(element: JsonElement): JsonElement {
         if (condition) {
             return JsonNull
         }
        ...
    }
}

Right now, if I attempt that the deserialization fails with:

kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject as the serialized body of XXX, but had class kotlinx.serialization.json.JsonNull

marcosalis avatar May 04 '22 16:05 marcosalis