kotlinx.serialization and JSON

kotlinx.serialization and JSON in Kotlin: An assembled chair cannot be posted through a letterbox.

The Analogy: The Flat-Pack Furniture Kit

An assembled chair cannot be posted through a letterbox. To ship it, the manufacturer flat-packs it: the chair is broken down into flat, individually labelled parts, laid in a box with a parts list and an instruction sheet, so a bulky three-dimensional object becomes a compact, transmissible package. At the far end, someone follows the labels and instructions to reassemble an identical chair. This is exactly what serialization does: an in-memory object, which occupies structured space and cannot travel over a wire, is flattened into a portable text form -- JSON -- and later rebuilt into an equivalent object. Kotlin's kotlinx.serialization is the flat-pack line: encodeToString boxes the object up, decodeFromString reassembles it.

The labels on the parts are what make reassembly possible. Each part is marked so it goes back in the right place, and the instruction sheet names them consistently at both ends. In serialization these labels are the field names; an object's properties are written out under their names and read back by matching them. You can relabel a part deliberately -- ship it as "seat-panel-A" even though the workshop calls it seat -- as long as both ends agree, which is what an explicit serial-name annotation does. And some parts are deliberately left out of the box because they are assembled fresh on site, such as a cached or derived value that need not travel; marking a property transient omits it from the package.

The instruction sheet also handles missing and surplus parts gracefully. If a standard part is not in the box, the instructions say to use the default one from the fittings bag -- a default value fills in for an absent field. If the box contains an extra part this model does not use, a sensible assembler sets it aside rather than refusing to build -- which is the "ignore unknown keys" setting that lets a decoder tolerate fields it does not recognise. This flexibility is what lets a producer and a consumer evolve at slightly different rates without every shipment failing.

The failure that leaves a customer with a pile of timber is a mismatch between the box and the instructions. Relabel a part on the packing line but forget to update the instruction sheet, and the assembler cannot find the part it is told to fit -- a serial-name that disagrees between producer and consumer. Add a new mandatory part to the design but ship an old box that lacks it, with no default in the fittings bag, and assembly cannot complete -- a new non-nullable field with no default, decoded against older JSON that predates it. Or try to flat-pack something that simply cannot be broken down and labelled -- a type with no serializer. In every case the flat-pack promise, that what is reassembled equals what was packed, breaks precisely where the two ends stopped agreeing.


Syntax or Core Structure

Annotate a class @Serializable, then Json.encodeToString flattens it to JSON and Json.decodeFromString rebuilds it. Data class fields are written in declaration order.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Point(val x: Int, val y: Int)

fun main() {
    val p = Point(3, 4)
    val text = Json.encodeToString(p)
    println(text)
    val back = Json.decodeFromString<Point>(text)
    println(back)
    println("round trip equal? " + (p == back))
}

Output:

{"x":3,"y":4}
Point(x=3, y=4)
round trip equal? true

@Serializable generates the code that flattens and rebuilds Point. encodeToString writes the fields in declaration order, producing the compact JSON {"x":3,"y":4}. decodeFromString<Point> reads that text and reconstructs a Point, whose data class toString prints "Point(x=3, y=4)". Because a data class compares by value, the reassembled object equals the original -- "round trip equal? true" -- which is the fidelity guarantee a flat-pack kit promises. The JSON field order is deterministic, following the class declaration.


Technical Depth: Annotations, Nesting, and Configuration

The serialization toolbox

A handful of annotations and Json settings shape how objects flatten and rebuild. The table lists the common ones.

FeatureEffect
@Serializablegenerate the serializer for a class
@SerialName("x")use x as the JSON key instead of the property name
@Transientomit a property from JSON (must have a default)
default valuefills in when a key is absent on decode
encodeDefaults = truewrite fields even when equal to their default
ignoreUnknownKeys = truetolerate JSON keys with no matching field

By default a field equal to its default is omitted from the output, and an unknown key in the input is an error -- both behaviours are configurable on a Json instance.

Renaming, defaults, and transient fields

@SerialName relabels a key, a default fills an absent one, and @Transient keeps a property out of the JSON entirely.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class User(
    @SerialName("user_id") val id: Int,
    val name: String = "anon",
    @Transient val cached: Int = 0
)

fun main() {
    val u = User(id = 7, name = "Ada", cached = 99)
    println(Json.encodeToString(u))
    val decoded = Json.decodeFromString<User>("""{"user_id":7}""")
    println(decoded)
}

Output:

{"user_id":7,"name":"Ada"}
User(id=7, name=anon, cached=0)

Encoding u writes id under the relabelled key "user_id", includes name because "Ada" is not its default, and omits cached entirely because it is @Transient -- so the value 99 never travels. Decoding the minimal {"user_id":7} sets id to 7, falls back to the default "anon" for the absent name, and gives cached its default 0. The reassembled object shows the transient field back at its default, a reminder that @Transient data does not survive a round trip.

Nested objects and lists

Serialization recurses: a @Serializable class containing other @Serializable types and lists flattens the whole tree.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Tag(val label: String)

@Serializable
data class Post(val title: String, val tags: List<Tag>)

fun main() {
    val post = Post("Hello", listOf(Tag("kotlin"), Tag("json")))
    println(Json.encodeToString(post))
}

Output:

{"title":"Hello","tags":[{"label":"kotlin"},{"label":"json"}]}

Post holds a title and a List<Tag>, and each Tag is itself @Serializable. Encoding produces nested JSON: the title, then a tags array of objects, each with its own label. The structure of the JSON mirrors the structure of the object exactly, and the order -- title before tags, and the tags in list order -- is deterministic.

Configuring the Json instance

A configured Json changes default handling: encodeDefaults writes default-valued fields, and ignoreUnknownKeys tolerates extra input keys.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Config(val host: String = "localhost", val port: Int = 8080)

val lenient = Json { encodeDefaults = true; ignoreUnknownKeys = true }

fun main() {
    println(lenient.encodeToString(Config()))
    val c = lenient.decodeFromString<Config>("""{"host":"db","port":5432,"extra":true}""")
    println(c)
}

Output:

{"host":"localhost","port":8080}
Config(host=db, port=5432)

With encodeDefaults = true, encoding a default Config() writes both fields even though they equal their defaults -- without it, the output would be an empty {}. With ignoreUnknownKeys = true, decoding JSON that carries an extra "extra" key does not fail; the unknown key is set aside and Config(host=db, port=5432) is built from the recognised ones. These two settings are what let a strict schema coexist with slightly-out-of-step producers and consumers.

Polymorphic serialization of a sealed hierarchy

A @Serializable sealed type serializes each subtype with a class discriminator -- by default a type key -- so a list of mixed subtypes round-trips correctly.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
sealed interface Shape {
    @Serializable @SerialName("circle")
    data class Circle(val radius: Int) : Shape

    @Serializable @SerialName("square")
    data class Square(val side: Int) : Shape
}

fun main() {
    val shapes: List<Shape> = listOf(Shape.Circle(5), Shape.Square(4))
    val text = Json.encodeToString(shapes)
    println(text)
    println(Json.decodeFromString<List<Shape>>(text))
}

Output:

[{"type":"circle","radius":5},{"type":"square","side":4}]
[Circle(radius=5), Square(side=4)]

Because Shape is a @Serializable sealed type, each element is tagged with a discriminator: the @SerialName on each subtype supplies the value, and the default key is "type". Encoding the mixed list writes {"type":"circle","radius":5} and {"type":"square","side":4}, so the decoder knows which subtype to rebuild. Decoding restores the exact subtypes, printing [Circle(radius=5), Square(side=4)]. The discriminator is what makes polymorphism survive the flat-pack: it labels which kind of part each object is.


Real World Example: A Field Added Without a Default

An app persists Account objects as JSON. Version 1 had id and name. In version 2 the team adds a required email field, declaring it non-nullable with no default because "every account has an email now." The new code reads and writes v2 JSON perfectly -- and then someone tries to load an account stored by version 1.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

@Serializable
data class Account(val id: Int, val name: String, val email: String)  // email added in v2

fun main() {
    val v2Json = """{"id":1,"name":"Ada","email":"ada@x.io"}"""
    println(Json.decodeFromString<Account>(v2Json))

    val v1Json = """{"id":1,"name":"Ada"}"""   // stored before email existed
    val outcome = try {
        Json.decodeFromString<Account>(v1Json).toString()
    } catch (e: SerializationException) {
        "decode failed: email missing"
    }
    println(outcome)
}

Output:

Account(id=1, name=Ada, email=ada@x.io)
decode failed: email missing

New data works flawlessly. The v2 JSON carries all three fields, so decodeFromString rebuilds Account(id=1, name=Ada, email=ada@x.io). Every test written against current data passes, and the change looks complete.

Old data breaks. The v1 JSON predates email and simply does not contain that key. Because email is non-nullable and has no default, the decoder has nothing to put there and cannot complete the object, so it throws a SerializationException (specifically a missing-field error) -- caught here and reported as "decode failed: email missing". In production, every account saved before the upgrade would fail to load.

The genuine design flaw is evolving a serialized schema by adding a mandatory field with no default, which is the analogy's new required part shipped in a fittings bag that older boxes never carried. The convenience of a clean non-nullable field costs backward compatibility with all previously-written JSON. The fix is to make new fields tolerant of old data: give email a default (val email: String = "") so absent keys fill in, or make it nullable (val email: String? = null) when "unknown" is a real state, and combine that with ignoreUnknownKeys so newer producers do not break older consumers either. The broader limitation is that any persisted or transmitted schema must evolve additively -- new fields optional or defaulted, existing fields never repurposed -- because somewhere there is always older data that predates your latest change, and a decoder is only as compatible as its least forgiving required field.

Common Mistakes

  1. Adding a required field with no default. A new non-nullable field with no default breaks decoding of all older JSON that lacks it. Give new fields a default or make them nullable.
  1. Assuming @Transient data survives a round trip. A transient property is omitted from JSON, so after decode it returns to its default. Do not put must-persist data in a transient field.
  1. Forgetting encodeDefaults when defaults must appear. By default, fields equal to their default are omitted. If a consumer needs every field present, set encodeDefaults = true.
  1. Not setting ignoreUnknownKeys for evolving inputs. A stricter default rejects unknown keys, so a newer producer with extra fields breaks an older consumer. Enable it when tolerating extra keys is desired.
  1. Relabelling with @SerialName on only one side. If producer and consumer disagree on the JSON key, the field will not match. Keep the serial name consistent across both ends.
  1. Serializing a type without a serializer. A property whose type is not @Serializable (and has no custom serializer) fails to compile or throws. Annotate nested types or provide a serializer.
  1. Relying on JSON key order for logic. While kotlinx.serialization writes fields in declaration order, JSON objects are semantically unordered; never depend on key order when parsing.
  1. Repurposing an existing field's meaning. Changing what a field represents while keeping its name silently corrupts old data. Add a new field instead and migrate.
  1. Creating a new Json { } per call. Building a configured Json instance is not free; create one and reuse it rather than constructing it on every encode or decode.

Best Practices

  • Evolve schemas additively: new fields optional or defaulted, existing fields never repurposed, so older data still decodes.
  • Give fields sensible defaults or nullability to tolerate absent keys, and enable ignoreUnknownKeys to tolerate surplus ones.
  • Keep @SerialName values identical on producer and consumer, treating the wire name as a shared contract.
  • Reserve @Transient for genuinely derived or cached data that need not persist, and never for state you must recover.
  • Set encodeDefaults deliberately based on whether consumers require every field to be present.
  • Annotate all nested types @Serializable so the whole object tree flattens without a missing-serializer error.
  • Reuse a single configured Json instance rather than building one per call.
  • Verify round-trip fidelity in tests -- encode then decode and assert equality -- to catch silent field loss early.

Practice Exercises

  1. Make a @Serializable data class with two fields, encode an instance to JSON, decode it back, and assert the round trip is equal.
  1. Add @SerialName to rename a field and @Transient to a third field, then confirm from the JSON that the key is renamed and the transient field is absent, and that it returns to its default after decode.
  1. Reproduce the schema flaw: add a required non-nullable field with no default, decode older JSON that lacks it, and observe the failure. Then fix it with a default or nullability and confirm the old JSON decodes.
  1. Configure a Json { ignoreUnknownKeys = true } and decode JSON containing an extra key, confirming the known fields are read and the extra key is ignored.