CodeBlanks Logo Icon CodeBlanks

Json

Learn Json.encodeToString and decodeFromString.

The Json object

Json is the object that produces and reads JSON with kotlinx.serialization. Json.encodeToString(value) produces JSON, Json.decodeFromString<T>(text) reads JSON.

Example: val json = Json.encodeToString(user). This turns user into {"name":"Alex"}. With Json { prettyPrint = true } you configure it. The default Json object produces compact JSON. decodeFromString<User>(json) declares the target class via the type parameter.

decodeFromString

decodeFromString turns a JSON string into a Kotlin object. The type parameter declares the target class.

Example: val user = Json.decodeFromString<User>("{"name":"Alex"}"). This turns the JSON string into a User object. JSON field names must match Kotlin property names. Mismatched fields throw. With ignoreUnknownKeys = true unknown fields are skipped. This is useful for external JSON.

Practice Use Json encodeToString

Define @Serializable data class User(val name: String). Inside main, set val user = User("Alex"), produce JSON with val json = Json.encodeToString(user), and print println("JSON produced").

Starter code

Main.kt
// Use Json
// write here
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json

fun main() {
    
}

Sample solution

Main.kt
@Serializable
data class User(val name: String)

fun main() {
    val user = User("Alex")
    val json = Json.encodeToString(user)
    println("JSON produced")
}

Expected output

JSON produced

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the encodeToString call

Question
val json = Json.____(user)
Answer
val json = Json.encodeToString(user)

Explanation: encodeToString turns an object into JSON.

2 Match Json methods

Term Meaning
encodeToString Object to JSON
decodeFromString JSON to object
Json Configuration
prettyPrint Readable output

3 Which direction does Json.decodeFromString work?

  • Object to JSON
  • JSON to object Correct answer
  • Object to XML
  • XML to object

Explanation: decodeFromString turns a JSON string into an object.

All lessons in Advanced