JSON

suggest change

The standard way to work with JSON in Kotlin is kotlinx.serialization. It is made by JetBrains, works on every Kotlin platform (JVM, Android, JS, Native), and does not use reflection. A compiler plugin generates a serializer for each class marked @Serializable.

This article covers:

For JSON in HTTP requests see HTTP client. For JSON configuration files see Configuration files.

Setup

The serialization plugin version must match your Kotlin version. The runtime library is versioned separately. In build.gradle.kts:

plugins {
    kotlin("jvm") version "2.4.21"
    kotlin("plugin.serialization") version "2.4.21"
}

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

If you forget the plugin, the code still compiles but fails at runtime with Serializer for class 'User' is not found.

Encoding and decoding

Mark the class with @Serializable, then call Json.encodeToString() and Json.decodeFromString():

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class User(val id: Int, val name: String, val email: String?, val tags: List<String>)

fun main() {
    val user = User(1, "Alice", null, listOf("admin", "dev"))

    val text = Json.encodeToString(user)
    println(text)

    val back = Json.decodeFromString<User>(text)
    println(back)
    println(back == user)
}

Output:

{"id":1,"name":"Alice","email":null,"tags":["admin","dev"]}
User(id=1, name=Alice, email=null, tags=[admin, dev])
true

Configuring Json

Json { ... } creates a configured instance. Creating one is expensive, so store it in a top-level val and reuse it:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
data class Settings(
    val theme: String = "light",
    val fontSize: Int = 12,
    val plugins: List<String> = emptyList(),
    val proxy: String? = null,
)

val pretty = Json {
    prettyPrint = true
    encodeDefaults = true
}

val lenientReader = Json {
    ignoreUnknownKeys = true
    isLenient = true
    allowTrailingComma = true
    allowComments = true
}

fun main() {
    println(Json.encodeToString(Settings(fontSize = 14)))
    println(pretty.encodeToString(Settings(fontSize = 14)))

    val input = """
        {
          // user settings
          theme: dark,
          "fontSize": 16,
          "unknownField": 42,
        }
    """
    println(lenientReader.decodeFromString<Settings>(input))
}

Output:

{"fontSize":14}
{
    "theme": "light",
    "fontSize": 14,
    "plugins": [],
    "proxy": null
}
Settings(theme=dark, fontSize=16, plugins=[], proxy=null)

Options you will use most often:

Option Default Effect
prettyPrint false Multi-line output, 4-space indent (prettyPrintIndent changes it)
ignoreUnknownKeys false Skip JSON keys with no matching property, instead of throwing
encodeDefaults false Write properties whose value equals the default
explicitNulls true When false, null values are omitted and missing nullable fields decode as null
coerceInputValues false Use the default value for null in non-null fields and for unknown enum values
isLenient false Accept unquoted keys and string values
allowTrailingComma false Accept [1, 2,] and {"a": 1,}
allowComments false Accept // and /* */ comments
classDiscriminator "type" Key name used for polymorphic types
namingStrategy null Map property names, e.g. camelCase to snake_case

When reading JSON from an API you don't control, ignoreUnknownKeys = true is almost always what you want. Otherwise a new field added on the server breaks your client.

Note the first line of output: with the default encodeDefaults = false, only fontSize was written because every other property had its default value.

Defaults and nulls

A property with a default value is optional when decoding. A property without one is required, even if it is nullable:

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

enum class Color { RED, GREEN }

@Serializable
data class Item(val name: String, val note: String? = null, val color: Color = Color.RED, val qty: Int = 1)

@Serializable
data class Profile(val name: String, val bio: String?)

val withDefaults = Json { encodeDefaults = true }
val noNulls = Json { encodeDefaults = true; explicitNulls = false }
val forgiving = Json { coerceInputValues = true }

fun main() {
    println(Json.encodeToString(Item("pen")))
    println(withDefaults.encodeToString(Item("pen")))
    println(noNulls.encodeToString(Item("pen")))

    // explicitNulls = false also lets a missing nullable property decode as null
    println(noNulls.decodeFromString<Profile>("""{"name":"Eve"}"""))

    // null for a non-null property and an unknown enum value fall back to defaults
    println(forgiving.decodeFromString<Item>("""{"name":"cup","qty":null,"color":"PURPLE"}"""))
}

Output:

{"name":"pen"}
{"name":"pen","note":null,"color":"RED","qty":1}
{"name":"pen","color":"RED","qty":1}
Profile(name=Eve, bio=null)
Item(name=cup, note=null, color=RED, qty=1)

coerceInputValues is useful for APIs that send null for "no value" or add new enum constants over time.

Renaming and skipping properties

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNames

enum class Status {
    @SerialName("active") ACTIVE,
    @SerialName("banned") BANNED,
}

@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class Account(
    @SerialName("user_id") val userId: Long,
    @JsonNames("login", "user_name") val username: String,
    val status: Status = Status.ACTIVE,
    @Transient val cachedScore: Int = 0,
)

fun main() {
    val a = Account(42, "bob", Status.BANNED, cachedScore = 99)
    val s = Json.encodeToString(a)
    println(s)
    println(Json.decodeFromString<Account>(s))
    println(Json.decodeFromString<Account>("""{"user_id":7,"login":"carol"}"""))
}

Output:

{"user_id":42,"username":"bob","status":"banned"}
Account(userId=42, username=bob, status=BANNED, cachedScore=0)
Account(userId=7, username=carol, status=ACTIVE, cachedScore=0)

To rename every property instead of annotating each one, use a naming strategy:

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonNamingStrategy

@Serializable
data class Order(val orderId: Int, val customerName: String, val totalCents: Long)

@OptIn(ExperimentalSerializationApi::class)
val snake = Json { namingStrategy = JsonNamingStrategy.SnakeCase }

fun main() {
    val s = snake.encodeToString(Order(1, "Dana", 1999))
    println(s)
    println(snake.decodeFromString<Order>(s))
}

Output:

{"order_id":1,"customer_name":"Dana","total_cents":1999}
Order(orderId=1, customerName=Dana, totalCents=1999)

JsonNamingStrategy.KebabCase is also available. A @SerialName on a property takes priority over the strategy.

Collections, maps and value classes

Lists, sets, maps, arrays, Pair and Triple of serializable types work out of the box:

import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.MapSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json

@Serializable
data class Score(val player: String, val points: Int)

@Serializable
@JvmInline
value class UserId(val raw: Long)

@Serializable
data class Session(val user: UserId, val ttl: Int)

fun main() {
    val scores = listOf(Score("ann", 10), Score("ben", 7))
    val text = Json.encodeToString(scores)
    println(text)
    println(Json.decodeFromString<List<Score>>(text))

    val totals: Map<String, Int> = mapOf("ann" to 10, "ben" to 7)
    println(Json.encodeToString(totals))
    println(Json.decodeFromString<Map<String, Int>>("""{"x":1,"y":2}"""))

    println(Json.encodeToString(setOf(3, 1, 2)))
    println(Json.encodeToString(Pair("a", 1)))

    // explicit serializers, without reified type parameters
    val ser = ListSerializer(Score.serializer())
    println(Json.decodeFromString(ser, text).size)
    val mapSer = MapSerializer(String.serializer(), Int.serializer())
    println(Json.encodeToString(mapSer, totals))

    // value classes are encoded as the wrapped value
    println(Json.encodeToString(Session(UserId(9001), 3600)))
}

Output:

[{"player":"ann","points":10},{"player":"ben","points":7}]
[Score(player=ann, points=10), Score(player=ben, points=7)]
{"ann":10,"ben":7}
{x=1, y=2}
[3,1,2]
{"first":"a","second":1}
2
{"ann":10,"ben":7}
{"user":9001,"ttl":3600}

Working with JsonElement

When the JSON shape is dynamic, or you only need a couple of fields from a large document, parse it into a tree with parseToJsonElement(). The tree is made of:

import kotlinx.serialization.json.*

fun main() {
    val text = """
        {"repo":"kotlinx.serialization","stars":5600,"archived":false,
         "owner":{"login":"Kotlin","id":1446536},
         "topics":["json","kotlin","serialization"],"license":null}
    """
    val root = Json.parseToJsonElement(text).jsonObject

    val stars = root["stars"]!!.jsonPrimitive.int
    val login = root["owner"]!!.jsonObject["login"]!!.jsonPrimitive.content
    val topics = root["topics"]!!.jsonArray.map { it.jsonPrimitive.content }
    val archived = root["archived"]?.jsonPrimitive?.booleanOrNull
    val license = root["license"]?.jsonPrimitive?.contentOrNull

    println("stars=$stars login=$login archived=$archived license=$license")
    println(topics)
    println(root.keys)
    println(root["missing"])
    println(root["license"] is JsonNull)
}

Output:

stars=5600 login=Kotlin archived=false license=null
[json, kotlin, serialization]
[repo, stars, archived, owner, topics, license]
null
true

Building JSON

buildJsonObject and buildJsonArray create trees with a small DSL. A JsonElement can also be a property of a @Serializable class, which is handy for a free-form part of an otherwise typed message:

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

@Serializable
data class Event(val type: String, val payload: JsonObject)

fun main() {
    val obj = buildJsonObject {
        put("id", 17)
        put("name", "deploy")
        put("dryRun", false)
        put("comment", null as String?)
        putJsonObject("meta") {
            put("region", "eu-west-1")
        }
        putJsonArray("hosts") {
            add("web1")
            add("web2")
        }
    }
    println(obj)

    // modify: JsonObject is immutable, build a new one
    val updated = JsonObject(obj + ("name" to JsonPrimitive("rollback")))
    println(updated["name"])

    // JsonElement fields hold free-form parts of a typed object
    val e = Event("job", obj)
    val s = Json.encodeToString(e)
    println(Json.decodeFromString<Event>(s).payload["hosts"])

    // convert between JsonElement and typed objects
    val el: JsonElement = Json.encodeToJsonElement(Event("ping", JsonObject(emptyMap())))
    println(el)
    println(Json.decodeFromJsonElement<Event>(el))
}

Output:

{"id":17,"name":"deploy","dryRun":false,"comment":null,"meta":{"region":"eu-west-1"},"hosts":["web1","web2"]}
"rollback"
["web1","web2"]
{"type":"ping","payload":{}}
Event(type=ping, payload={})

encodeToJsonElement() and decodeFromJsonElement() convert between typed objects and trees without going through a string. A common pattern is to parse into a tree, look at one field to decide the type, then decode the tree into that type.

Polymorphism with sealed classes

To serialize a value whose static type is an interface or base class, kotlinx.serialization needs to record which subclass it is. For a sealed hierarchy this is automatic. A "type" key with the class's serial name is added to each object:

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

@Serializable
sealed interface Shape

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

@Serializable
@SerialName("rect")
data class Rect(val w: Double, val h: Double) : Shape

@Serializable
data class Drawing(val shapes: List<Shape>)

fun main() {
    val d = Drawing(listOf(Circle(1.5), Rect(2.0, 3.0)))
    val s = Json.encodeToString(d)
    println(s)

    val back = Json.decodeFromString<Drawing>(s)
    for (shape in back.shapes) {
        val area = when (shape) {
            is Circle -> Math.PI * shape.radius * shape.radius
            is Rect -> shape.w * shape.h
        }
        println("%s area=%.2f".format(shape, area))
    }

    val custom = Json { classDiscriminator = "kind" }
    println(custom.encodeToString<Shape>(Circle(1.0)))
}

Output:

{"shapes":[{"type":"circle","radius":1.5},{"type":"rect","w":2.0,"h":3.0}]}
Circle(radius=1.5) area=7.07
Rect(w=2.0, h=3.0) area=6.00
{"kind":"circle","radius":1.0}

Custom serializers

Types you don't own, such as java.time.LocalDate or java.util.UUID, have no built-in serializer. Write a KSerializer and attach it with @Serializable(with = ...):

import java.time.Instant
import java.time.LocalDate
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
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
import kotlinx.serialization.json.Json

object LocalDateSerializer : KSerializer<LocalDate> {
    override val descriptor: SerialDescriptor =
        PrimitiveSerialDescriptor("java.time.LocalDate", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: LocalDate) =
        encoder.encodeString(value.toString())

    override fun deserialize(decoder: Decoder): LocalDate =
        LocalDate.parse(decoder.decodeString())
}

object EpochSecondsSerializer : KSerializer<Instant> {
    override val descriptor = PrimitiveSerialDescriptor("EpochSeconds", PrimitiveKind.LONG)
    override fun serialize(encoder: Encoder, value: Instant) = encoder.encodeLong(value.epochSecond)
    override fun deserialize(decoder: Decoder): Instant = Instant.ofEpochSecond(decoder.decodeLong())
}

@Serializable
data class Invoice(
    val number: String,
    @Serializable(with = LocalDateSerializer::class) val due: LocalDate,
    @Serializable(with = EpochSecondsSerializer::class) val createdAt: Instant,
)

fun main() {
    val inv = Invoice("INV-7", LocalDate.of(2026, 11, 30), Instant.ofEpochSecond(1_760_000_000))
    val s = Json.encodeToString(inv)
    println(s)
    println(Json.decodeFromString<Invoice>(s))
}

Output:

{"number":"INV-7","due":"2026-11-30","createdAt":1760000000}
Invoice(number=INV-7, due=2026-11-30, createdAt=2025-10-09T08:53:20Z)

Errors

Decoding failures throw SerializationException, which extends IllegalArgumentException. The message includes the offset and a JSON path to the bad value:

import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json

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

fun parse(s: String): Point? =
    try {
        Json.decodeFromString<Point>(s)
    } catch (e: SerializationException) {
        println("error: ${e.message?.lineSequence()?.first()}")
        null
    }

fun main() {
    println(parse("""{"x":1,"y":2}"""))
    parse("""{"x":1}""")
    parse("""{"x":1,"y":"two"}""")
    parse("""{"x":1,"y":2,"z":3}""")
    parse("""{"x":1,"y":2""")
    println(SerializationException::class.java.superclass.simpleName)
}

Output:

Point(x=1, y=2)
error: Field 'y' is required for type with serial name 'Point', but it was missing at path: $
error: Unexpected JSON token at offset 12: Unexpected symbol 't' in numeric literal at path: $.y
error: Unexpected JSON token at offset 14: Encountered an unknown key 'z' at path: $
error: Expected end of the object '}', but had 'EOF' instead at path: $
IllegalArgumentException

The full message has a second line with a hint, e.g. suggesting ignoreUnknownKeys = true for the unknown key case. The example prints only the first line.

Validate business rules in an init block. An exception thrown there propagates out of decodeFromString():

@Serializable
data class Port(val value: Int) {
    init {
        require(value in 1..65535) { "port out of range: $value" }
    }
}

Files and streams

On the JVM, encodeToStream() and decodeFromStream() read and write OutputStream / InputStream directly, without building a whole String first. decodeToSequence() reads a stream of top-level values lazily, which suits large arrays and newline-delimited JSON (NDJSON) logs:

import java.io.File
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromStream
import kotlinx.serialization.json.decodeToSequence
import kotlinx.serialization.json.encodeToStream

@Serializable
data class LogLine(val level: String, val msg: String)

@OptIn(ExperimentalSerializationApi::class)
fun main() {
    val file = File.createTempFile("logs", ".json")
    val lines = listOf(LogLine("INFO", "started"), LogLine("WARN", "disk 91%"))

    file.outputStream().use { Json.encodeToStream(lines, it) }
    println(file.readText())

    val back: List<LogLine> = file.inputStream().use { Json.decodeFromStream(it) }
    println(back)

    // newline-delimited JSON (one object per line), read lazily
    val ndjson = File.createTempFile("logs", ".ndjson")
    ndjson.writeText(lines.joinToString("\n") { Json.encodeToString(it) })
    ndjson.inputStream().use { input ->
        Json.decodeToSequence<LogLine>(input)
            .filter { it.level == "WARN" }
            .forEach { println("warning: ${it.msg}") }
    }
    file.delete()
    ndjson.delete()
}

Output:

[{"level":"INFO","msg":"started"},{"level":"WARN","msg":"disk 91%"}]
[LogLine(level=INFO, msg=started), LogLine(level=WARN, msg=disk 91%)]
warning: disk 91%

These functions are marked experimental, hence the @OptIn. For small files, Json.decodeFromString<T>(file.readText()) is perfectly fine.

Jackson

Jackson is the most widely used JSON library on the JVM and the default in Spring Boot. It uses reflection, so classes need no annotations, but it only runs on the JVM. Add the Kotlin module, otherwise Jackson can't construct data classes without a no-argument constructor and ignores default values and nullability:

dependencies {
    implementation("tools.jackson.module:jackson-module-kotlin:3.2.3")
}

Jackson 3 moved to the tools.jackson package, but annotations stay in com.fasterxml.jackson.annotation:

import com.fasterxml.jackson.annotation.JsonProperty
import tools.jackson.module.kotlin.jacksonObjectMapper
import tools.jackson.module.kotlin.readValue

data class Book(
    val title: String,
    @JsonProperty("page_count") val pages: Int,
    val subtitle: String? = null,
)

fun main() {
    val mapper = jacksonObjectMapper()

    val s = mapper.writeValueAsString(Book("Kotlin in Action", 360))
    println(s)

    val b: Book = mapper.readValue("""{"title":"Atomic Kotlin","page_count":630}""")
    println(b)

    val list: List<Book> = mapper.readValue("""[{"title":"A","page_count":1}]""")
    println(list)

    val tree = mapper.readTree("""{"a":{"b":[10,20]}}""")
    println(tree["a"]["b"][1].asInt())

    println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(mapOf("ok" to true)))
}

Output:

{"title":"Kotlin in Action","page_count":360,"subtitle":null}
Book(title=Atomic Kotlin, pages=630, subtitle=null)
[Book(title=A, pages=1, subtitle=null)]
20
{
  "ok" : true
}

Which one to use:

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents