CodeBlanks Logo Icon CodeBlanks

JSON deserialization

Learn JSON deserialization with kotlinx.serialization.

JSON deserialization

JSON deserialization turns JSON text from the server into a Kotlin object. In Ktor the ContentNegotiation plugin does this with kotlinx.serialization.

You add @Serializable to a data class; when the client calls response.body<User>() the JSON becomes a User object. Example: @Serializable data class User(val name: String, val age: Int). JSON field names must match Kotlin property names. If they differ, use @SerialName to map them.

Reading an object with body()

To read an object from an HttpResponse call response.body<User>(). The generic parameter declares the target type.

Example: val user: User = client.get(url).body(). This call uses the ContentNegotiation plugin; without it the call throws. The return type is checked at compile time; mismatched JSON throws at runtime. For a list response use body<List<User>>(). The plugin maps the JSON shape to the Kotlin type automatically.

Practice Define a Serializable User class

Define a data class User(val name: String) marked with @Serializable. Inside main, print println("User class ready").

Starter code

Main.kt
// JSON deserialization
// write here
import kotlinx.serialization.Serializable

fun main() {
    
}

Sample solution

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

fun main() {
    println("User class ready")
}

Expected output

User class ready

Questions and answers

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

1 Complete the annotation name

Question
@____
data class User(val name: String)
Answer
@Serializable
data class User(val name: String)

Explanation: @Serializable marks the class.

2 Which annotation is needed to deserialize JSON to a Kotlin object?

  • @Serializable Correct answer
  • @JsonProperty
  • @SerializedName
  • @Json

Explanation: @Serializable is required for kotlinx.serialization.

3 Match deserialization parts

Term Meaning
@Serializable Marks the class
data class Data class
.body() Gets object
@SerialName Maps field name

All lessons in Advanced