JSON to Kotlin Data Class Generator

Generate Kotlin data classes from any JSON instantly. Get idiomatic Kotlin code with proper nullability, optional kotlinx.serialization or Gson annotations, and correct type inference. Free, no signup required.

What are Kotlin Data Classes?

Kotlin data classes are a powerful language feature designed specifically for holding data. By prefixing a class declaration with the data keyword, the Kotlin compiler automatically generates several critical methods based on the primary constructor properties: equals() and hashCode() for value equality, toString() for human-readable output, copy() for creating modified copies, and componentN() functions for destructuring declarations.

Compare a Java POJO for a user with three fields (requiring a constructor, six getter/setter methods, equals, hashCode, and toString - approximately 50 lines of boilerplate) to the equivalent Kotlin data class:

data class User(
    val id: Int,
    val name: String,
    val email: String,
    val isActive: Boolean = true
)

One line of Kotlin replaces dozens of lines of Java. The data keyword gives you structural equality, a useful toString, and a copy function automatically.

Data classes also integrate seamlessly with Kotlin's null safety system. Properties declared as val name: String are guaranteed non-null at compile time. Properties declared as val name: String? can be null and must be handled explicitly with null checks, the safe call operator ?., or the Elvis operator ?:. This eliminates an entire class of NullPointerException bugs that plague Java codebases.

kotlinx.serialization vs Gson for Kotlin

Two serialization libraries dominate JSON handling in Kotlin projects. The choice between them depends on your project type and constraints.

kotlinx.serialization is the officially supported library from JetBrains. It is the recommended choice for all new Kotlin and Android projects. Key characteristics:

Gson is the older Java library from Google, widely used in Android apps before kotlinx.serialization matured. Key characteristics:

For any new Android or Kotlin backend project starting today, kotlinx.serialization is the clear choice. For existing Retrofit-based Android apps already using Gson, migrating is beneficial but not urgent.

How to Use the JSON to Kotlin Generator

Generating Kotlin data classes from a JSON payload takes only seconds:

  1. Get a JSON sample from your REST API, Postman, or test data
  2. Click "Open JSON to Kotlin Generator" above to open the tool
  3. Paste the JSON into the input panel
  4. Select your serialization library: kotlinx.serialization or Gson
  5. The generator outputs the Kotlin data class definitions immediately
  6. Copy the generated code into your Android Studio or IntelliJ project
  7. Add the required dependencies if not already present

For kotlinx.serialization, add to your build.gradle.kts:

plugins {
    kotlin("plugin.serialization") version "1.9.0"
}

dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
}

Then annotate your data class with @Serializable and deserialize with Json.decodeFromString<MyClass>(jsonString).

Android Use Cases for JSON to Kotlin

Android development is one of the most common contexts for converting JSON to Kotlin data classes. Here are the key scenarios where this generator saves significant time:

Frequently Asked Questions

What are Kotlin data classes?

Kotlin data classes are classes prefixed with the data keyword that the compiler treats specially. The compiler automatically generates equals(), hashCode(), toString(), and copy() methods based on the properties declared in the primary constructor. They are the idiomatic Kotlin way to represent value objects and JSON models - far more concise than equivalent Java POJOs. Data classes work directly with Kotlin's null safety system, allowing you to express nullable vs non-nullable fields at the type level.

What is the difference between kotlinx.serialization and Gson for Kotlin?

kotlinx.serialization is the official Kotlin library that processes annotations at compile time via a compiler plugin. It fully understands Kotlin's type system including nullability and default parameter values, works with code obfuscation (R8/ProGuard) without special rules, and supports Kotlin Multiplatform. Gson is a Java reflection-based library that does not understand Kotlin nullability and can silently violate null contracts. For any new Kotlin project, kotlinx.serialization is strongly preferred. Gson is only appropriate for legacy Android codebases where migration is not feasible.

How does the generator handle nullable fields in Kotlin data classes?

JSON fields that contain null values or that may be absent from the response are generated as nullable Kotlin types, such as String?, Int?, or Boolean?. Fields that have a consistent value across the sample JSON are generated as non-nullable types. Optional fields that may be missing are given default values (typically = null for nullable types) so that kotlinx.serialization can deserialize partial JSON without a MissingFieldException. You can adjust nullability after generation based on your knowledge of the actual API contract.

How are nested JSON objects handled in Kotlin data class generation?

Each nested JSON object generates a separate Kotlin data class. The parent data class holds a property of the nested class type. For example, a JSON field "profile": {"avatarUrl": "...", "bio": "..."} generates a Profile data class and a val profile: Profile property in the parent. JSON arrays of objects generate List<T> properties. All data classes are output together so you can copy the entire block into a single Kotlin file. The @SerialName annotation is added automatically whenever a JSON key uses snake_case and the Kotlin property name uses camelCase.

Ready to generate your Kotlin data classes?

Free, instant, 100% private. No account needed.

JSON to Kotlin Data Class

Kotlin data classes are the idiomatic way to model JSON in Kotlin. With kotlinx.serialization, they integrate seamlessly with Android, Ktor, and Compose.

JSON Input → Kotlin Data Class

// JSON
{"userId": 1, "displayName": "Alice", "isPremium": true, "balance": 99.50}

// Kotlin (kotlinx.serialization)
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.SerialName

@Serializable
data class User(
    @SerialName("userId") val userId: Int,
    @SerialName("displayName") val displayName: String,
    @SerialName("isPremium") val isPremium: Boolean,
    @SerialName("balance") val balance: Double
)

// Deserialize
val user = Json.decodeFromString<User>(jsonString)
println(user.displayName) // Alice

Kotlin JSON Library Comparison

LibraryAnnotationNotes
kotlinx.serialization@SerializableOfficial JetBrains, Kotlin-native, Multiplatform
Gson@SerializedNameGoogle, Java interop, no compile-time safety
Moshi@JsonSquare, Kotlin-friendly, codegen or reflection
Jackson@JsonPropertyMost feature-rich, good for complex scenarios

Kotlin Null Safety with JSON

// Nullable fields use ?
@Serializable
data class User(
    val name: String,        // required — throws if missing
    val email: String?,      // optional — null if missing
    val age: Int = 0        // has default — uses 0 if missing
)

// Lenient parsing for partial JSON
val json = Json { ignoreUnknownKeys = true; isLenient = true }
val user = json.decodeFromString<User>(partialJson)

Kotlin Data Classes for JSON: Complete Guide

This example shows the full workflow from JSON input to generated Kotlin data classes and usage with both kotlinx.serialization and Gson.

{
  "id": 1,
  "name": "Alice",
  "email": "alice@example.com",
  "address": {
    "city": "London",
    "postcode": "SW1A 1AA"
  },
  "tags": ["admin", "user"],
  "active": true
}
// Generated Kotlin data classes
import kotlinx.serialization.Serializable

@Serializable
data class Address(
    val city: String,
    val postcode: String
)

@Serializable
data class User(
    val id: Int,
    val name: String,
    val email: String,
    val address: Address,
    val tags: List<String>,
    val active: Boolean
)

// Deserialize with kotlinx.serialization
val user = Json.decodeFromString<User>(jsonString)
println(user.name) // "Alice"

// Deserialize with Gson
val user = Gson().fromJson(jsonString, User::class.java)

// Serialize back to JSON
val jsonOutput = Json.encodeToString(user)

Handling Optional and Nullable Fields in Kotlin

// Option 1: Nullable type with default null
@Serializable
data class Product(
    val id: Int,
    val name: String,
    val description: String? = null,  // optional — null if missing
    val price: Double,
    val discount: Double? = null
)

// Option 2: Default values for absent fields
@Serializable
data class Config(
    val timeout: Int = 30,        // default 30 if not in JSON
    val retries: Int = 3,
    val debug: Boolean = false
)

Also useful: JWT Decoder | JSON Validator | JSON Formatter | JSON to Java | JSON to Go | JSON to C# | JSON to PHP