abstract class JsonTransformingSerializer<T : Any>(tSerializer: KSerializer<T>) : KSerializer<T>

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 JsonDecoder and JsonEncoder, i.e. serializers derived from this class work only with Json format.

There are two methods in which JSON transformation can be defined: transformSerialize and transformDeserialize. You can override one or both of them. Consult their documentation for details.

Usage example:

data class Example(
@Serializable(UnwrappingJsonListSerializer::class) val data: String
// Unwraps a list to a single object
object UnwrappingJsonListSerializer :
JsonTransformingSerializer<String>(String.serializer()) {
override fun transformDeserialize(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"}""")



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>)


A serializer for type T. Determines JsonElement which is passed to transformSerialize. Should be able to parse JsonElement from transformDeserialize function. Usually, default serializer is sufficient.


Link copied to clipboard
fun <T : Any> JsonTransformingSerializer(tSerializer: KSerializer<T>)


Link copied to clipboard
override fun deserialize(decoder: Decoder): T
Link copied to clipboard
override fun serialize(encoder: Encoder, value: T)


Link copied to clipboard
open override val descriptor: SerialDescriptor

A descriptor for this transformation. By default, it delegates to tSerializer's descriptor.