How to Parse JSON in Kotlin

← All guides

kotlinx.serialization is Kotlin's official, multiplatform JSON library. Annotate a data class with @Serializable and use Json.decodeFromString / encodeToString.

Deserialize into a data class

Mark the class @Serializable and call Json.decodeFromString with the target type.

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

@Serializable
data class User(val name: String, val roles: List<String>)

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

Serialize and pretty-print

encodeToString serializes; configure a Json instance with prettyPrint = true for readable output.

kotlin
val json = Json.encodeToString(user)                 // compact
val pretty = Json { prettyPrint = true }.encodeToString(user)

Handle unknown keys

By default extra JSON keys throw. Allow them with ignoreUnknownKeys.

kotlin
val lenient = Json { ignoreUnknownKeys = true }
val user = lenient.decodeFromString<User>(text)

Frequently Asked Questions

kotlinx.serialization is the official choice and works on all Kotlin targets. Gson and Moshi are also popular in Android projects.

Use the JSON to Kotlin tool to generate @Serializable data classes from a sample JSON document.

Annotate the property with @SerialName("json_key") to map a JSON key to a differently named Kotlin property.

Related Tools