Loading JSON to Kotlin Data Class Converter...
Loading JSON to Kotlin Data Class Converter...
Convert JSON to Kotlin data classes with null safety, default values, and serialization annotations. Perfect for Android development, API integration, and Kotlin Multiplatform projects.
Everything you need to know about converting JSON to Kotlin data classes
I've been building Android apps since the days of Eclipse and Java. When Kotlin arrived in 2017, I was skeptical at first. But after writing my first data class, I was hooked. No more Lombok, no more boilerplate getters and setters, no more findViewById — Kotlin was a breath of fresh air.
But one thing that still annoyed me? Parsing JSON from REST APIs. Every new endpoint meant writing a new data class. Every API change meant updating fields. And with Kotlin's strict null safety, forgetting a ? could crash your app.
That's why I built this JSON to Kotlin data class converter. After working on a large e-commerce Android app with 50+ API endpoints, I knew there had to be a better way. This tool is the result — and it's saved me and my team hundreds of hours.
// JSON Input
{
"id": 123,
"name": "John Doe",
"email": "john@example.com",
"isActive": true
}
// Generated Kotlin Data Class
import kotlinx.serialization.Serializable
@Serializable
data class User(
val id: Int,
val name: String,
val email: String,
@SerialName("isActive") val isActive: Boolean
)
Data classes in Kotlin are special classes designed to hold data. When you mark a class with the data keyword, Kotlin automatically generates:
equals() and hashCode() methodstoString() methodcopy() method for creating modified copiescomponentN() functions for destructuring declarationsHere's what a manual Java POJO looks like versus a Kotlin data class:
// Java (35+ lines)
public class User {
private String name;
private String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
@Override
public boolean equals(Object o) { ... }
@Override
public int hashCode() { ... }
@Override
public String toString() { ... }
}
// Kotlin (3 lines!)
data class User(
val name: String,
val email: String
)
That's 35+ lines of Java vs 3 lines of Kotlin. This is why Kotlin data classes are revolutionary.
Understanding how JSON types map to Kotlin types is crucial. Here's the complete mapping our converter uses:
| JSON Type | Kotlin Type | Nullable Type | Example | Notes |
|---|---|---|---|---|
| string | String | String? | "Hello" | Always nullable if field can be null |
| integer | Int | Int? | 42 | Use Long for large numbers |
| number | Double | Double? | 29.99 | Float also available |
| boolean | Boolean | Boolean? | true/false | Non-nullable by default |
| array | List<T> | List<T>? | [1,2,3] | MutableList optional |
| object | Data class | Data class? | {"key":"value"} | Nested data class |
| null | Nothing? | Type? | null | Always nullable |
Let me show you a real example from an e-commerce Android app I worked on. Here's a typical order JSON from a REST API:
{
"orderId": "ORD-12345",
"customer": {
"id": 1001,
"name": "Jane Smith",
"email": "jane@example.com"
},
"items": [
{
"productId": "P-100",
"name": "Wireless Headphones",
"quantity": 2,
"unitPrice": 79.99,
"totalPrice": 159.98
}
],
"totalAmount": 159.98,
"status": "COMPLETED",
"createdAt": "2024-03-20T10:15:00Z"
}
Our converter generates these Kotlin data classes:
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
import java.util.Date
@Serializable
data class Order(
@SerialName("orderId") val orderId: String,
val customer: Customer,
val items: List<Item>,
@SerialName("totalAmount") val totalAmount: Double,
val status: String,
@SerialName("createdAt") val createdAt: String
)
@Serializable
data class Customer(
val id: Int,
val name: String,
val email: String
)
@Serializable
data class Item(
@SerialName("productId") val productId: String,
val name: String,
val quantity: Int,
@SerialName("unitPrice") val unitPrice: Double,
@SerialName("totalPrice") val totalPrice: Double
)
This is production-ready code. Just add your serialization library dependency and you're done.
JetBrains' official serialization library. Zero reflection, compile-time safety, Kotlin Multiplatform support. This is what I recommend for most projects.
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
}
Popular in Android development. Uses code generation for performance. Excellent if you're already using Retrofit or OkHttp.
// build.gradle.kts
dependencies {
implementation("com.squareup.moshi:moshi:1.15.0")
ksp("com.squareup.moshi:moshi-kotlin-codegen:1.15.0")
}
Google's library. Works, but uses reflection which is slower. Still widely used in older projects.
// build.gradle.kts
dependencies {
implementation("com.google.code.gson:gson:2.10.1")
}
One of Kotlin's best features is null safety. The type system distinguishes between nullable and non-nullable types. This eliminates NullPointerExceptions at compile time.
Our converter automatically detects which fields can be null in your JSON and adds the ? modifier accordingly. For example:
// JSON with optional fields
{
"id": 1,
"name": "John",
"email": null, // Can be null
"middleName": null // Can be null
}
// Generated Kotlin
data class User(
val id: Int, // Non-nullable (always present)
val name: String, // Non-nullable (always present)
val email: String?, // Nullable (can be null)
val middleName: String? // Nullable (can be null)
)
Real-world APIs have nested objects. Our converter automatically generates inner data classes for nested structures:
// JSON with nesting
{
"user": {
"name": "John",
"address": {
"street": "123 Main St",
"city": "Boston"
}
}
}
// Generated Kotlin
@Serializable
data class User(
val name: String,
val address: Address
) {
@Serializable
data class Address(
val street: String,
val city: String
)
}
JSON arrays become Kotlin Lists. Our converter uses immutable List by default (best practice), but you can choose MutableList if needed:
// JSON array
{
"users": [
{"id": 1, "name": "John"},
{"id": 2, "name": "Jane"}
]
}
// Generated Kotlin
data class UserList(
val users: List<User> // Immutable list - recommended
)
// Alternative with mutable list
data class UserList(
val users: MutableList<User> // Mutable if you need modifications
)
In Android, if you need to pass data between Activities or Fragments, your data class needs to implement Parcelable. Our converter can add this automatically:
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
@Serializable
data class User(
val id: Int,
val name: String,
val email: String
) : Parcelable
Add this to your module's build.gradle:
plugins {
id("kotlin-parcelize")
}
I've done this both ways countless times. Here's the real difference:
Manual Process for a moderate API response (15 fields, nested objects):
Automated Process with this converter:
Prefer val (read-only) over var (mutable) unless you have a good reason. Immutable data classes are thread-safe and easier to reason about.
Add default values to prevent null issues and simplify instance creation:
data class User(
val id: Int = 0,
val name: String = "",
val email: String = "",
val isActive: Boolean = false
)
When JSON uses snake_case (created_at) and Kotlin uses camelCase (createdAt), use @SerialName:
data class Post(
@SerialName("created_at") val createdAt: String
)
If your data class has more than 10-15 fields, consider splitting it into smaller classes.
typealias UserId = Long
typealias ProductList = List<Product>
data class Order(
val userId: UserId,
val products: ProductList
)
Always mark fields that can be null with ?. Otherwise, your app will crash when JSON doesn't include that field.
Mutable data classes can lead to bugs. Use val by default, switch to var only when needed.
Default values prevent errors when creating instances manually and make testing easier.
Be consistent with camelCase for Kotlin properties, use @SerialName to map from snake_case JSON.
@Test
fun testUserSerialization() {
val json = """{"id":1,"name":"John","email":"john@example.com"}"""
val user = Json.decodeFromString<User>(json)
assertEquals(1, user.id)
assertEquals("John", user.name)
}
Data classes automatically generate equals(), hashCode(), toString(), and copy() methods. They're specifically designed for holding data and are perfect for JSON models.
val is read-only (immutable) — you can't change the value after creation. var is mutable — you can change it. Use val unless you need mutation.
Kotlin distinguishes between String (cannot be null) and String? (can be null). The compiler forces you to handle null cases, preventing NullPointerException.
Absolutely! Generate data classes for Retrofit, add Parcelable for passing data between components, and use with kotlinx.serialization or Moshi.
Yes! The generated code works with Kotlin Multiplatform when using kotlinx.serialization, which is fully multiplatform.
Yes! All conversion happens in your browser. Your JSON never leaves your device. No servers, no tracking, no data collection.
Transform your JSON into Kotlin data classes in just a few clicks
Paste Your JSON Copy-paste your JSON data into the editor, upload a .json file, or click on any example above.
Configure Options Choose your serialization library (kotlinx.serialization, Moshi, or Gson), set package name, and customize class naming.
Generate Data Class Click Convert or press Ctrl+Enter. Our parser creates Kotlin data classes with proper null safety and default values.
Copy or Download Copy the generated code to your clipboard or download as a .kt file. Use it immediately in your Kotlin project.
Built for real-world Kotlin development
How developers use JSON to Kotlin Data Class Converter
Complex API response with 25 fields and 3 nested objects? Generated in 2 seconds. Manual writing? 20 minutes.
Proper Kotlin types every time. No more ClassCastException or type mismatch errors.
Never forget a ? again. Our generator correctly identifies nullable fields and adds safe types.
Adds proper annotations for kotlinx.serialization, Moshi, or Gson — your choice.
API changed? Paste new JSON, re-convert, and replace. No manual refactoring of 20 fields.
Optional Parcelable implementation for passing data between Activities and Fragments.
See how professional Kotlin data classes should be structured. Learn by example.
Generated code follows Kotlin conventions, includes proper formatting, and is ready to ship.
Real questions from Kotlin developers
A Kotlin data class is a special class designed to hold data. It automatically generates equals(), hashCode(), toString(), copy(), and componentN() functions, reducing boilerplate code significantly.
Yes, completely free! No signup, no credit card, no 'free trial' limitations. Built by a Kotlin developer for Kotlin developers.
Yes! The converter analyzes your JSON and adds '?' to fields that can be null. This is one of Kotlin's best features — compile-time null safety.
Full support for kotlinx.serialization (official JetBrains), Moshi (Square), and Gson (Google). You choose what works for your project.
Nested JSON objects become nested Kotlin data classes. The converter automatically generates inner classes with proper indentation and serialization annotations.
JSON arrays become List<T> with proper generic types. For example, [1,2,3] becomes List<Int>. You can also choose MutableList if needed.
Never. The entire conversion happens in your browser using JavaScript. Your JSON never touches our servers — complete privacy guaranteed.
Absolutely! The generated data classes work perfectly with Retrofit, Moshi, kotlinx.serialization, and can be made Parcelable for passing between Activities.
val (value) is read-only and immutable. var (variable) is mutable. Our converter uses val by default for immutability — a Kotlin best practice.
Yes! When JSON uses snake_case (like 'user_id') and you want camelCase (userId), the converter adds @SerialName annotations automatically.
Primitive fields (Int, Boolean, Double) get default values (0, false, 0.0). This prevents null issues when creating instances manually.
Our tool handles JSON files up to 10MB efficiently. For larger files, we recommend splitting them into smaller logical chunks.