Map JSON String Values to Kotlin Enum Classes
Learn how to convert JSON string fields with a fixed set of values into Kotlin enum classes. Covers @SerialName annotations, fallback handling, and custom serializers.
Detailed Explanation
JSON Strings to Kotlin Enums
When a JSON field can only contain a fixed set of string values (like "active", "inactive", "pending"), a Kotlin enum class provides compile-time exhaustiveness checking.
Example JSON
{
"id": 1,
"name": "Alice",
"status": "active",
"role": "admin"
}
Generated Kotlin
@Serializable
enum class Status {
@SerialName("active") ACTIVE,
@SerialName("inactive") INACTIVE,
@SerialName("pending") PENDING
}
@Serializable
enum class Role {
@SerialName("admin") ADMIN,
@SerialName("editor") EDITOR,
@SerialName("viewer") VIEWER
}
@Serializable
data class User(
val id: Int,
val name: String,
val status: Status,
val role: Role
)
Why Enums?
Using String for enum-like fields means any typo compiles successfully. With enum classes:
when (user.status) {
Status.ACTIVE -> enableFeatures()
Status.INACTIVE -> showReactivation()
Status.PENDING -> showVerification()
// Compiler warns if a case is missing!
}
@SerialName for JSON Mapping
@SerialName maps the JSON string to the Kotlin enum constant. Without it, kotlinx.serialization expects the enum constant name as-is ("ACTIVE"), which rarely matches the lowercase API values.
Handling Unknown Values
APIs may add new enum values over time. Use a custom serializer to handle unknowns gracefully:
@Serializable
enum class Status {
@SerialName("active") ACTIVE,
@SerialName("inactive") INACTIVE,
@SerialName("pending") PENDING,
UNKNOWN;
companion object {
fun fromJson(value: String): Status =
entries.find { it.name.equals(value, ignoreCase = true) } ?: UNKNOWN
}
}
Gson Approach
enum class Status {
@com.google.gson.annotations.SerializedName("active") ACTIVE,
@com.google.gson.annotations.SerializedName("inactive") INACTIVE,
@com.google.gson.annotations.SerializedName("pending") PENDING
}
Enums make your Kotlin code self-documenting and protect against invalid state, which is especially valuable in Android apps where runtime crashes frustrate users.
Use Case
Mobile apps and backend services commonly receive status fields, role types, and category values from APIs. Mapping these to Kotlin enums enables exhaustive when-expressions and prevents invalid state bugs in production.
Try It — JSON to Kotlin
Related Topics
Model Polymorphic JSON with Kotlin Sealed Classes
Advanced Patterns
Convert Simple JSON to a Kotlin Data Class
Basic Data Classes
Kotlin Serialization Annotations for JSON Mapping
Serialization
Handle Nullable JSON Fields in Kotlin Data Classes
Basic Data Classes
Configure JSON Naming Strategy in Kotlin Serialization
Serialization