Kotlin JSON to Data Class: The Modern Way
Forget Java boilerplate. With Kotlin data classes, you get immutable, type-safe JSON mapping in one line. Learn kotlinx.serialization and Moshi.
Why Kotlin Data Classes Beat Java POJOs
Java POJO (50+ lines)
public class User {
private String name;
private int age;
// getters...
// setters...
// equals...
// hashCode...
// toString...
}Kotlin Data Class (1 line)
data class User(
val name: String,
val age: Int
)Immutable by default. Auto-generated equals, hashCode, toString, copy().
Option 1: kotlinx.serialization (Official)
What is kotlinx.serialization? It's Kotlin's official serialization library by JetBrains. It uses compile-time code generation for maximum performance and type safety.
@Serializable
data class User(
val name: String,
val age: Int
)
// 2. Parse JSON
val user = Json.decodeFromString<User>(jsonString)
Option 2: Moshi (Android Recommended)
Moshi by Square is the go-to JSON library for Android. It respects Kotlin null-safety and integrates seamlessly with Retrofit.
@JsonClass(generateAdapter = true)
data class User(
@Json(name = "user_name") val name: String,
val age: Int
)
// Parse JSON
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson(jsonString)
Kotlin Null Safety: The Game Changer
Why Gson fails with Kotlin: Gson uses unsafe Java reflection that bypasses Kotlin's null checks. A non-null String can become null at runtime, causing crashes.
val name: String = null // CRASH!Gson can cause this
val name: String? = null // SafeMoshi respects this
Default Values for Missing Fields
Unlike Java, Kotlin supports default parameter values. If a JSON field is missing, use the default:
val name: String,
val age: Int = 0, // Default if missing
val isActive: Boolean = true
)
Library Comparison
| Feature | kotlinx.serialization | Moshi | Gson |
|---|---|---|---|
| Kotlin Null Safety | ✓ Full | ✓ Full | ✗ Unsafe |
| Default Values | ✓ Supported | Requires config | ✗ No |
| Android Size | Medium | Small | Small |
Common Questions
Can I use Kotlin with Jackson?
Yes, add the jackson-module-kotlin dependency. It adds support for data classes and default values.
How to rename JSON fields?
Use @SerialName("field_name") for kotlinx.serialization or @Json(name = "field_name") for Moshi.
Generate Kotlin Data Classes Instantly
Our converter supports Kotlin output with @Serializable and Moshi annotations.