Skip to content

Support nullable types in JsonTransformingSerializer #1927

@marcosalis

Description

@marcosalis

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions