0Pricing
Kotlin Academy · Lesson

Custom Serializers

Handle special types.

Custom Serializers is a free Kotlin Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Custom Serializers?

Some types have no built-in serializer: java.util.Date, LocalDate, UUID, or types from third-party libraries.

A custom serializer defines how such a type maps to and from a serial form.

The KSerializer Interface

A custom serializer implements KSerializer<T> with three members: descriptor, serialize, and deserialize.

import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

A Serializer for LocalDate

Map a LocalDate to and from an ISO string. The descriptor declares it as a primitive string.

import java.time.LocalDate
import kotlinx.serialization.KSerializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

object LocalDateSerializer : KSerializer<LocalDate> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING)
    override fun serialize(encoder: Encoder, value: LocalDate) =
        encoder.encodeString(value.toString())
    override fun deserialize(decoder: Decoder): LocalDate =
        LocalDate.parse(decoder.decodeString())
}

Using @Serializable(with = ...)

Apply the serializer to a specific property with @Serializable(with = ...).

import java.time.LocalDate
import kotlinx.serialization.Serializable

@Serializable
data class Event(
    val name: String,
    @Serializable(with = LocalDateSerializer::class)
    val date: LocalDate
)

File-Level @UseSerializers

To avoid annotating every property, declare serializers once per file with @file:UseSerializers.

@file:UseSerializers(LocalDateSerializer::class)

import kotlinx.serialization.UseSerializers
import java.time.LocalDate
import kotlinx.serialization.Serializable

@Serializable
data class Event(val name: String, val date: LocalDate)

Contextual Serialization

Register serializers globally in the Json { } module and mark properties @Contextual. The serializer is resolved at runtime from the module.

import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import java.time.LocalDate

@Serializable
data class Event(val name: String, @Contextual val date: LocalDate)

Registering a SerializersModule

Build a module that binds the type to its serializer and pass it to Json.

import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.SerializersModule
import java.time.LocalDate

val module = SerializersModule {
    contextual(LocalDate::class, LocalDateSerializer)
}
val json = Json { serializersModule = module }

Composite Serializers

For multi-field types, use encodeStructure / decodeStructure with a structured descriptor instead of a primitive one.

import kotlinx.serialization.descriptors.buildClassSerialDescriptor
import kotlinx.serialization.descriptors.element

val descriptor = buildClassSerialDescriptor("Color") {
    element<Int>("r")
    element<Int>("g")
    element<Int>("b")
}

Surrogate Pattern

A simpler alternative: serialize a private surrogate data class that the compiler already supports, then map to and from your real type. Less boilerplate than manual encode/decode.

import kotlinx.serialization.Serializable

@Serializable
private data class ColorSurrogate(val r: Int, val g: Int, val b: Int)

Choosing an Approach

Pick the lightest approach that fits:

  • @Serializable(with=) — one property
  • @UseSerializers — whole file
  • @Contextual + module — app-wide, runtime-resolved
  • Surrogate — composite types with minimal code

Primitive vs Structured Descriptor

The descriptor must match how you encode:

  • Single value (string/int) → PrimitiveSerialDescriptor
  • Multiple fields → buildClassSerialDescriptor

A mismatch causes runtime serialization errors.

Quick Check

You want to serialize a single LocalDate as one ISO string. Which descriptor is appropriate?

Recap

Custom serializers handle types the plugin doesn't know:

  • Implement KSerializer<T> with descriptor + serialize + deserialize
  • Apply via @Serializable(with=), @UseSerializers, or @Contextual + module
  • Match the descriptor kind to your encoding

That completes the Serialization course.

Frequently asked questions

Is the “Custom Serializers” lesson free?

Yes — the full text of “Custom Serializers” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “Custom Serializers”?

Handle special types. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Custom Serializers” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. kotlinx.serialization Setup
  2. Serializable Classes
  3. JSON Encoding and Decoding
  4. Custom Serializers
← Back to Kotlin Academy