Convert Simple JSON to a Kotlin Data Class
Learn how to convert a flat JSON object into a Kotlin data class with val properties. Covers String, Int, Double, and Boolean type mapping from JSON.
Detailed Explanation
From JSON to a Kotlin Data Class
The simplest JSON-to-Kotlin conversion maps a flat JSON object to a data class. Each JSON key becomes a val property with an inferred Kotlin type.
Example JSON
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"active": true,
"score": 98.5
}
Generated Kotlin
data class User(
val id: Int,
val name: String,
val email: String,
val active: Boolean,
val score: Double
)
Type Mapping Rules
| JSON type | Kotlin type |
|---|---|
| string | String |
| integer | Int (or Long for large values) |
| decimal | Double |
| boolean | Boolean |
| null | String? (nullable) |
Why Data Classes?
Kotlin data class automatically generates equals(), hashCode(), toString(), copy(), and destructuring declarations. This makes them ideal for holding JSON data because you get value-based comparison and easy cloning out of the box.
Deserialization with Kotlinx.serialization
@Serializable
data class User(
val id: Int,
val name: String,
val email: String,
val active: Boolean,
val score: Double
)
val user = Json.decodeFromString<User>(jsonString)
Deserialization with Gson
val user = Gson().fromJson(jsonString, User::class.java)
This is the foundation of all JSON-to-Kotlin conversions. Understanding this basic mapping is essential before moving on to nested objects, nullable fields, and collections.
Use Case
When building Android apps or Kotlin backend services that consume REST APIs, you frequently receive simple JSON payloads for user profiles, settings, or status responses. Converting them to data classes gives you type safety and IDE autocompletion.
Try It — JSON to Kotlin
Related Topics
Convert Nested JSON Objects to Kotlin Data Classes
Basic Data Classes
Handle Nullable JSON Fields in Kotlin Data Classes
Basic Data Classes
Convert JSON Arrays to Kotlin Lists
Collections
Kotlin Serialization Annotations for JSON Mapping
Serialization
Use Default Values in Kotlin Data Classes for Missing JSON Fields
Serialization