Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 134 ยท Text, Files and Time

kotlinx.serialization Basics

Learn kotlinx.serialization: the @Serializable plugin, Json configuration, @SerialName, defaults, nullable fields, sealed polymorphism and how it works, with runnable stand-ins.

Almost every program has to turn objects into text or bytes and back again: to send them over a network, store them in a file or keep them in a cache. This is called serialization (objects to data) and deserialization (data to objects). In the lesson Working with JSON Text you wrote a parser by hand. In real projects you use kotlinx.serialization, the official Kotlin library for this job.

The library has one unusual property: it does not use reflection at run time. A compiler plugin looks at your @Serializable classes while compiling and generates a small serializer for each one. That makes it fast, safe on Kotlin Multiplatform and friendly to code shrinkers. The price is a Gradle setup (see Gradle Basics), so the library is not available in our in-browser runner. The library examples below are read-only. To still practice the ideas with runnable code, the TryIt blocks build small stand-ins that follow the same design.

Setting it up

Two things are needed in a Gradle build: the compiler plugin, which generates the serializers, and the runtime library with the JSON format:

Kotlin
// read-only example: build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.0"
    kotlin("plugin.serialization") version "2.4.0"   // same version as Kotlin
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}

The plugin version always matches the Kotlin version. The library version is independent, so check the latest release when you start a project.

Your first serializable class

Mark a class with @Serializable and the plugin does the rest. Then the Json object turns instances into text and back:

Kotlin
// read-only example: needs the serialization plugin
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

@Serializable
data class Book(val title: String, val pages: Int, val tags: List<String> = emptyList())

fun main() {
    val book = Book("Kotlin in Practice", 320, listOf("kotlin", "jvm"))

    val text = Json.encodeToString(book)
    println(text)   // {"title":"Kotlin in Practice","pages":320,"tags":["kotlin","jvm"]}

    val back = Json.decodeFromString<Book>(text)
    println(back == book)   // true: data classes compare by content
}

Every property in the primary constructor is serialized, and the property names become the JSON keys. Nested @Serializable classes, lists, maps, sets, enums and the basic types all work out of the box. Properties that are not in the constructor, and properties marked @Transient, are skipped (a transient property needs a default value, because decoding cannot fill it).

Here is how data flows through the two directions:

flowchart LR
    A["Book object"] -->|"encodeToString"| B["JSON text"]
    B -->|"decodeFromString"| C["Book object"]
    P["Compiler plugin"] -.->|"generates Book.serializer()"| A
    P -.-> C

The compiler plugin generates a serializer for each class at build time; the Json format uses it in both directions.

How it works, in a runnable stand-in

The generated serializer describes the class (its name and its fields) and knows how to write each field. You can build the same idea by hand. The stand-in below is not the real library, but it uses the same design: one small interface per type, and an encoder that only has to know about the format.

Kotlin A hand-written serializer (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real library goes further: it works for decoding as well, supports many formats (not only JSON) because the serializer talks to an abstract encoder, and checks types at compile time. But the lesson is the same: the cost of reflection is paid once, by the compiler, not by every request.

Configuring Json

Json is a configurable object. You rarely use the default Json in a real application. Instead you create one instance with the options you need and reuse it, because a Json instance is thread-safe:

Kotlin
// read-only example
val format = Json {
    ignoreUnknownKeys = true    // do not fail when the input has extra keys
    prettyPrint = true          // multi-line output with indentation
    encodeDefaults = true       // also write properties that equal their default
    explicitNulls = false       // leave out null properties instead of writing "x": null
    coerceInputValues = true    // use the default when the input has null or an unknown enum
    isLenient = false           // keep quotes and comma rules strict (the default)
}

The most useful option is ignoreUnknownKeys. By default, decoding fails when the JSON contains a key that the class does not know. For data from an API you do not control, that is too strict, because the other side may add fields at any time. Be deliberate, though: the default strictness also catches typos in your own configuration files.

Annotations

A few annotations cover most needs:

Kotlin
// read-only example
import kotlinx.serialization.*

@Serializable
data class Account(
    @SerialName("user_name") val userName: String,   // JSON key differs from the Kotlin name
    val email: String? = null,                       // optional and nullable
    val roles: Set<String> = setOf("reader"),        // default used when the key is missing
    @Transient val cachedScore: Int = 0,             // never written or read
    @Required val id: Long = 0,                      // must be in the input, even though it has a default
)
  • @SerialName("...") renames a property (or a class, which matters for polymorphism). It is the standard fix for APIs that use snake_case while your Kotlin code uses camelCase.
  • A default value makes a property optional when decoding: if the key is missing, the default is used. A property without a default is required, and a missing key throws a SerializationException.
  • @Transient excludes a property. @Required makes a property mandatory even though it has a default.
  • A nullable type (String?) accepts null in the input. A nullable type with a default of null also accepts a missing key.
  • @Contextual and custom serializers handle types the library does not know, such as java.util.UUID or java.time.Instant. You write one KSerializer that converts to a string and attach it with @Serializable(with = ...).

Defaults and requirements follow the same rules you already know from default arguments and null safety. The next example imitates decoding with a missing key, a default and a required key:

Kotlin Required, optional and default fields (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Polymorphism with sealed classes

Serialization of a value whose exact type is only known at run time needs a class discriminator: an extra key such as "type" that says which subclass the object is. With a sealed hierarchy, the plugin knows all subclasses at compile time, so it works without any registration:

Kotlin
// read-only example
@Serializable
sealed interface Shape

@Serializable
@SerialName("circle")
data class Circle(val radius: Double) : Shape

@Serializable
@SerialName("rect")
data class Rect(val width: Double, val height: Double) : Shape

fun main() {
    val shapes: List<Shape> = listOf(Circle(1.5), Rect(2.0, 3.0))
    val text = Json.encodeToString(shapes)
    println(text)
    // [{"type":"circle","radius":1.5},{"type":"rect","width":2.0,"height":3.0}]

    val back = Json.decodeFromString<List<Shape>>(text)
    println(back == shapes)   // true
}

The discriminator key is called type by default and can be changed with classDiscriminator = "kind" in the Json configuration. For open hierarchies (interfaces and abstract classes that are not sealed), you register the subclasses in a SerializersModule. Sealed classes are the safer choice, since decoding an unknown "type" fails with a clear error instead of producing a wrong object.

The stand-in below shows what a discriminator does: the decoder reads type first and then chooses the right subclass. A when over the sealed type keeps both directions exhaustive.

Kotlin Choosing a subclass by discriminator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Other formats and common pitfalls

The same @Serializable classes can be written in other formats by swapping the format object: kotlinx-serialization-protobuf (compact binary), kotlinx-serialization-cbor, properties and community formats for YAML and TOML. This is the main reason for the design: your model stays the same, and only the format changes.

A few things trip up beginners:

  • Forgetting the plugin. Without kotlin("plugin.serialization"), @Serializable compiles but serializer() does not exist, and you get an "Serializer has not been found" error.
  • Enums and unknown values. An enum constant that is not in your class fails decoding unless you enable coerceInputValues and have a default.
  • Numbers. Decoding "age": 36.5 into an Int fails. Strict types are a feature.
  • Generated classes from the JVM only. Libraries like Jackson can serialize any Java object using reflection. kotlinx.serialization needs the annotation on your own classes (or a custom serializer for library classes).

When you want to inspect JSON without a class, use the JsonElement tree: Json.parseToJsonElement(text) gives you the same kind of tree as the hand-built sealed Json interface from Working with JSON Text, with jsonObject, jsonArray and jsonPrimitive accessors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the kotlinx.serialization compiler plugin do?

    The plugin generates the serializer code during compilation, so no reflection is needed when the program runs.
  2. 2. A property has no default value and the JSON input does not contain its key. What happens when decoding?

    A property without a default is required. A missing key is an error, unlike a property with a default value.
  3. 3. Which annotation maps the Kotlin property userName to the JSON key user_name?

    @SerialName changes the name used in the serialized form. @Transient excludes a property, and @Required makes it mandatory.
  4. 4. Why do sealed hierarchies work well for polymorphic JSON?

    The plugin sees every subclass of a sealed type and writes a type key into the output so the decoder can pick the right one.

Summary

  • kotlinx.serialization turns @Serializable classes into text or bytes and back, using serializers generated at compile time instead of reflection.
  • It needs the Gradle plugin and a format library, so the library examples are read-only here.
  • Create one configured Json { ... } instance (for example with ignoreUnknownKeys) and reuse it.
  • Use @SerialName to rename, default values for optional fields, @Transient to skip and @Required to insist.
  • Sealed classes give polymorphism with a type discriminator and no registration.
  • Other formats (Protobuf, CBOR) reuse the same annotated classes.

Next: Introduction to Coroutines