Kotlin

kotlinx.serialization — JSON Basics

admin by @admin ADMIN
2d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Compile-time code generation for JSON serialization. Annotate `@Serializable` on a data class; `Json.encodeToString` and `Json.decodeFromString` are typed.
Kotlin
Raw
// build.gradle.kts:
//   plugins { kotlin("plugin.serialization") version "1.9.+" }
//   implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.+")

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

@Serializable
data class User(val id: Int, val name: String, val email: String)

val json = Json {
    prettyPrint   = true
    ignoreUnknownKeys = true                  // tolerate extra fields from server
    encodeDefaults    = true
}

fun main() {
    val user = User(42, "Alice", "a@x.com")

    val text: String = json.encodeToString(user)
    println(text)
    // {
    //   "id": 42,
    //   "name": "Alice",
    //   "email": "a@x.com"
    // }

    val parsed: User = json.decodeFromString(text)
    println(parsed)

    // List<T> too
    val users = listOf(User(1, "A", "a@x"), User(2, "B", "b@x"))
    val arrayText = json.encodeToString(users)
    val back: List<User> = json.decodeFromString(arrayText)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.