Kotlin Academy · Lesson

Custom Serializers

Handle special types.

Lesson 4 of 413 steps

Custom Serializers is a free Kotlin Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, and your progress syncs across the web and the CoddyKit app. The Kotlin Academy course includes 4 lessons in total.

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.

Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Custom Serializers” lesson free?

Yes — any 3 lessons of the Kotlin Academy learning path, including “Custom Serializers”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Kotlin Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

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