kotlinx-serialization / kotlinx.serialization.json / JsonTransformingSerializer / <init>

<init>

(common, js, jvm, native) <init>(tSerializer: KSerializer<T>, transformationName: String)

Base class for custom serializers that allows manipulating an abstract JSON representation of the class before serialization or deserialization.

JsonTransformingSerializer provides capabilities to manipulate JsonElement representation directly instead of interacting with Encoder and Decoder in order to apply a custom transformation to the JSON. Please note that this class expects that Encoder and Decoder are implemented by JsonInput and JsonOutput, i.e. serializers derived from this class work only with Json format.

During serialization, this class first serializes original value with tSerializer to a JsonElement, then calls writeTransform method, which may contain a user-defined transformation, such as wrapping a value into JsonArray, filtering keys, adding keys, etc.

During deserialization, the opposite process happens: first, value from JSON stream is read to a JsonElement, second, user transformation in readTransform is applied, and then JSON tree is deserialized back to T with tSerializer.

Usage example:

@Serializable
data class Example(
    @Serializable(UnwrappingJsonListSerializer::class) val data: String
)
// Unwraps a list to a single object
object UnwrappingJsonListSerializer :
    JsonTransformingSerializer<String>(String.serializer(), "UnwrappingList") {
    override fun readTransform(element: JsonElement): JsonElement {
        if (element !is JsonArray) return element
        require(element.size == 1) { "Array size must be equal to 1 to unwrap it" }
        return element.first()
    }
}
// Now these functions both yield correct result:
Json.parse(Example.serializer(), """{"data":["str1"]}""")
Json.parse(Example.serializer(), """{"data":"str1"}""")

Parameters

T - A type for Kotlin property for which this serializer could be applied. Not the type that you may encounter in JSON. (e.g. if you unwrap a list to a single value T, use T, not List<T>)

tSerializer - A serializer for type T. Determines JsonElement which is passed to writeTransform. Should be able to parse JsonElement from readTransform function. Usually, default serializer is sufficient.

transformationName - A name for the particular implementation to fulfill SerialDescriptor.serialName uniqueness guarantee.