How to Parse JSON in Kotlin
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)