Working with JSON
Prerequisites: Data classes, Gradle basics
JSON is the most common format for sending data between programs. The standard Kotlin way to convert between JSON and your own classes is kotlinx.serialization, which generates the conversion code at compile time.
Setup
Add the serialization plugin and library to build.gradle.kts:
plugins {
kotlin("jvm") version "2.2.0"
kotlin("plugin.serialization") version "2.2.0"
}
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0")
}
Encoding and decoding
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
@Serializable
data class User(val name: String, val age: Int, val tags: List<String> = emptyList())
fun main() {
val user = User("Ada", 36, listOf("admin"))
val json = Json.encodeToString(user)
println(json)
val parsed = Json.decodeFromString<User>("""{"name":"Linus","age":28}""")
println(parsed)
}
{"name":"Ada","age":36,"tags":["admin"]}
User(name=Linus, age=28, tags=[])
@Serializabletells the compiler plugin to generate the conversion code.- Properties with default values may be missing from the JSON; others
must be present, or decoding throws a
SerializationException.
Configuring the parser
Real APIs send fields you don't care about, and often use different naming:
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
val json = Json {
ignoreUnknownKeys = true // don't fail on extra fields
prettyPrint = true // indented output
}
@Serializable
data class Repo(
@SerialName("full_name") val fullName: String,
@SerialName("stargazers_count") val stars: Int,
)
@SerialName maps a JSON key to a differently named property.
Paste a sample API response into the JSON Formatter to see its structure before writing the matching classes.
Alternatives
In Java-based projects you'll also meet Jackson and Moshi (common in older Android code). kotlinx.serialization is the natural choice for new Kotlin code, and the only one that works in Kotlin Multiplatform.
Common mistakes
- Forgetting the serialization plugin — the library alone isn't enough, and you'll get "Serializer for class 'User' is not found".
- Leaving
ignoreUnknownKeysoff when reading third-party APIs, so a new field added by the API breaks your app.