Skip to content
The App Code
How-to

Parse JSON in Kotlin

Decode JSON into data classes using the kotlinx.serialization library.

Also known as: kotlinx.serialization JSON, Kotlin decode JSON

beginner

Annotate a data class with @Serializable and call Json.decodeFromString<T>() to parse JSON into a typed Kotlin object.

What it is

The idiomatic modern approach on Android and Kotlin Multiplatform is the official kotlinx.serialization library. You mark a data class with @Serializable, and the compiler plugin generates the parsing code — no reflection at runtime.

Configure a reusable Json instance. Setting ignoreUnknownKeys = true is almost always what you want against real APIs, so that fields you don't model don't cause the parse to throw. Use @SerialName when a JSON key differs from your property name.

Worked example

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

@Serializable
data class User(
    val id: Int,
    @SerialName("full_name") val fullName: String
)

val json = Json { ignoreUnknownKeys = true }

fun main() {
    val text = """{ "id": 7, "full_name": "Ada Lovelace", "extra": true }"""
    val user = json.decodeFromString<User>(text)
    println(user.fullName) // Ada Lovelace
}

Failure mode — when it misleads

Without ignoreUnknownKeys = true, any extra field the server adds later throws a SerializationException, breaking a previously working app. Also remember to apply the kotlin("plugin.serialization") Gradle plugin — missing it produces a confusing "serializer not found" compile error.

Sources & further reading