@SerialName
- Kotlin course
- Advanced
- Lesson 27/83
- 5 min
Learn JSON key names with @SerialName.
What is @SerialName?
@SerialName is the annotation that changes the JSON counterpart of a property. It bridges a Kotlin property name and a JSON field name that differ.
Example: @Serializable data class User(@SerialName("user_name") val name: String). In this class the name property appears as user_name in JSON. When reading JSON it also looks for user_name. This adapts external JSON to existing Kotlin naming. The annotation goes right above the property declaration.
@SerialName usage examples
@SerialName is especially useful for JSON from APIs. JSON field names use snake_case while Kotlin uses camelCase.
Example: an API returns {"first_name": "Alex", "created_at": "2024-01-01"}. You write @SerialName("first_name") val firstName: String and @SerialName("created_at") val createdAt: String. This keeps Kotlin code readable while preserving JSON field names. Each property gets its own annotation. @SerialName only affects serialization; it does not change runtime behavior.
Practice Map a field with @SerialName
Define a data class User(@SerialName("user_name") val name: String) marked with @Serializable. Inside main, print println("User ready").
Starter code
// SerialName annotation
// write here
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
fun main() {
}Sample solution
@Serializable
data class User(@SerialName("user_name") val name: String)
fun main() {
println("User ready")
}Expected output
User ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match @SerialName parts
| Term | Meaning |
|---|---|
@SerialName |
Maps field name |
user_name |
JSON field |
name |
Kotlin property |
@Serializable |
Marks the class |
2 When is @SerialName used?
- When the class is sealed
- When the property is null
- When the Kotlin property name differs from the JSON field name Correct answer
- When prettyPrint is wanted
Explanation: @SerialName bridges a name difference.
3 Complete the @SerialName call
@Serializable
data class User(@____("user_name") val name: String)
@Serializable
data class User(@SerialName("user_name") val name: String)
Explanation: @SerialName sets the JSON field name.