Summary - kotlinx.serialization
- Kotlin course
- Advanced
- Lesson 30/83
- 5 min
Combine @Serializable, Json and @SerialName to write an API model.
Summary - kotlinx.serialization
This group covered @Serializable, Json, @SerialName, @Optional and polymorphic serialization. They bridge Kotlin and JSON.
You add @Serializable to a class, produce JSON with Json.encodeToString, read with Json.decodeFromString, map field names with @SerialName, give defaults with @Optional, and do polymorphic serialization with sealed classes. Together they form a solid data exchange layer.
Practice Summary: serialization
Define @Serializable data class User(val name: String). Inside main, set val user = User("Alex"), run val json = Json.encodeToString(user), and print println("Summary ready").
Starter code
// Summary: serialization
// write here
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
fun main() {
}Sample solution
@Serializable
data class User(val name: String)
fun main() {
val user = User("Alex")
val json = Json.encodeToString(user)
println("Summary ready")
}Expected output
Summary ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method turns JSON into a Kotlin object?
- encodeToString
- decodeFromString Correct answer
- toString
- stringify
Explanation: decodeFromString turns JSON into an object.
2 Match all serialization concepts
| Term | Meaning |
|---|---|
@Serializable |
Marks the class |
Json |
Produces and reads |
@SerialName |
Maps field name |
@Optional |
Default value |
polymorphic |
Type tag |