jsondecode.com logo

JSON in Kotlin — kotlinx.serialization & Gson

Kotlin has two popular approaches: kotlinx.serialization (the official Kotlin multiplatform library) and Gson (from Google). For new projects, kotlinx.serialization is recommended.

Parse JSON with kotlinx.serialization

Add the @Serializable annotation and use Json.decodeFromString<T>().

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

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

val json = """{"id":1,"name":"Alice","email":"alice@example.com"}"""
val user = Json.decodeFromString<User>(json)
println(user.name) // Alice

Serialize to JSON

Use Json.encodeToString() to convert a data class to a JSON string.

val user = User(id = 1, name = "Alice", email = "alice@example.com")

val json = Json.encodeToString(user)
// {"id":1,"name":"Alice","email":"alice@example.com"}

// Pretty-print
val prettyJson = Json { prettyPrint = true }
println(prettyJson.encodeToString(user))

Parse JSON with Gson

Gson is simpler for Android projects already using it. Add com.google.code.gson:gson.

import com.google.gson.Gson

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

val gson = Gson()

// Deserialize
val user = gson.fromJson(json, User::class.java)

// Serialize
val output = gson.toJson(user)

Format and validate your JSON instantly

Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.

Open JSON Formatter →