JSON deserialization
- Kotlin course
- Advanced
- Lesson 17/83
- 5 min
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
// JSON deserialization
// write here
import kotlinx.serialization.Serializable
fun main() {
}Sample solution
@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
@____
data class User(val name: String)
@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 |