JSON to Kotlin Data Class Generator

Generate Kotlin data classes from JSON with kotlinx.serialization annotations, nullable types, and nested class support.

What is JSON to Kotlin Data Class Generator?

Kotlin's data classes are the idiomatic way to model JSON API responses on Android and in backend Kotlin services (Ktor, Spring Boot with Kotlin). A data class automatically provides equals(), hashCode(), toString(), and copy() — things you'd write by hand in Java. But generating the class definition itself from a live API response still requires care: Kotlin's type system distinguishes nullable types (String?) from non-nullable (String), and if you get that wrong, your app either throws a NullPointerException at runtime or refuses to compile. This generator produces Kotlin data classes with the correct nullability, optional kotlinx.serialization annotations (@Serializable, @SerialName), and proper class ordering (nested classes before the parent that references them). If you use Gson or Moshi instead of kotlinx.serialization, disable the serialization option — the data class itself is valid for any Kotlin JSON library.

How to Use

  1. Set the root class name to match the concept (e.g. "UserProfile", "OrderResponse") — this will be the outermost data class name
  2. Enable "kotlinx.serialization" if you use the org.jetbrains.kotlinx:kotlinx-serialization-json library — it adds @Serializable to each class and @SerialName when field names differ
  3. Enable "snake_case" if your JSON uses snake_case keys (common in Python/Django APIs) and you want idiomatic Kotlin camelCase properties with @SerialName bridging the two
  4. Enable "Detect dates" to map ISO-8601 strings to kotlinx.datetime.Instant or LocalDate instead of plain String — add the kotlinx-datetime dependency if you use this
  5. Enable "Nullable types" to mark all fields as nullable (T?) — useful when the API is inconsistent and fields can be absent or null unexpectedly
  6. Paste your JSON and click "Generate Kotlin Code" — the output is ready to paste into an .kt file

Why Use This Tool?

Generates Kotlin data classes, not plain classes — you get equals(), hashCode(), copy(), and destructuring for free
Correctly marks nullable fields as T? based on null values in the sample, preventing NullPointerException at runtime
Compatible with kotlinx.serialization, Gson, Moshi, and Jackson — the data class structure works with all major Kotlin JSON libraries
Nested classes are ordered children-first, which is required in Kotlin (unlike Java, a type must be defined before it is referenced in a top-level context)
List<T> for JSON arrays with type inference from the first element
Runs entirely in the browser — your API response data never leaves your device

Tips & Best Practices

  • For Android Room database entities, you may want to separate your JSON data class from your database entity — use a mapping function rather than adding @Entity annotations to the generated class
  • If the JSON comes from a backend you control and uses snake_case (e.g. user_id), enabling snake_case + kotlinx.serialization adds @SerialName("user_id") on the userId property — cleaner than relying on a custom NamingStrategy
  • Kotlin's default values in data classes do not mix well with kotlinx.serialization unless you add @ExperimentalSerializationApi and use the explicit defaults mode — if you need default values, consider adding them manually after generating
  • For Android development, the generated classes work directly with Retrofit + kotlinx.serialization or Retrofit + Gson converters without modification
  • Use a real API response as input, not a hand-crafted example — type inference for Int vs Long, or whether a field is nullable, depends on the actual runtime values

Frequently Asked Questions

What is the complete JSON type → Kotlin type mapping?

JSON string → String (or Instant/LocalDate if date detection is on). JSON integer → Int (values fitting Int range) or Long (large values). JSON float → Double. JSON boolean → Boolean. JSON null → T? where T is inferred from non-null occurrences. JSON array → List<T> with T inferred from the first element. JSON object → a named data class. Heterogeneous arrays → List<Any>.

What is kotlinx.serialization and how does it differ from Gson?

kotlinx.serialization is Kotlin's official serialization library, maintained by JetBrains. Unlike Gson (which uses runtime reflection), kotlinx.serialization generates serialization code at compile time via Kotlin compiler plugins. This makes it faster and fully compatible with Kotlin Multiplatform (KMP) projects. Gson requires no annotations but is slower and does not support KMP. If you are starting a new Android or KMP project, kotlinx.serialization is the recommended choice.

Why does Kotlin distinguish String from String? (nullable vs non-nullable)?

Kotlin's type system treats nullable and non-nullable types as distinct types at compile time. String cannot hold null — the compiler prevents it. String? can be null but requires explicit null-checking (?.operator or !! assertion) before use. When consuming JSON, if a field can ever be null, it must be typed as T? or the deserialization will throw a NullPointerException at runtime. This generator infers nullability from the sample data — if you see a null value in the JSON, the corresponding Kotlin property is marked T?.

When should I NOT use data classes for JSON models?

Skip data classes when your JSON model needs to be a Room @Entity — Room has specific restrictions on data class features and foreign key handling. Also skip them for complex sealed class hierarchies where different JSON shapes map to different Kotlin types (use @SerialName on sealed class subclasses instead). For extremely large JSON objects with 50+ fields, consider splitting into smaller focused classes.

Is my data sent to a server?

No. All code generation runs entirely in your browser. Your JSON data never leaves your device.

Real-world Examples

Parsing an Android local cache table response

Android apps using Room often fetch data from a REST API and store it locally. The generated data class models the API response; a separate @Entity class is used for the database. Here is a typical product catalog response from a shopping app backend.

Input
{
  "productId": "prod_7821",
  "name": "Wireless Noise-Cancelling Headphones",
  "price": 79.99,
  "currency": "USD",
  "inStock": true,
  "stockCount": 143,
  "category": "Electronics",
  "imageUrl": "https://cdn.example.com/products/7821.jpg",
  "tags": ["wireless", "audio", "sale"],
  "specs": {
    "batteryHours": 30,
    "weightGrams": 250,
    "bluetoothVersion": "5.2"
  }
}
Output
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName

@Serializable
data class Specs(
    val batteryHours: Int,
    val weightGrams: Int,
    val bluetoothVersion: String
)

@Serializable
data class Product(
    val productId: String,
    val name: String,
    val price: Double,
    val currency: String,
    val inStock: Boolean,
    val stockCount: Int,
    val category: String,
    val imageUrl: String,
    val tags: List<String>,
    val specs: Specs
)

Handling a nullable user profile from a social API

When a user has not completed their profile, the API returns null for the profile object and bio field. Enabling "Nullable types" marks them as Profile? and String? respectively — the Android UI can then show a placeholder instead of crashing on a null dereference.

Input
{
  "userId": "u_9920",
  "username": "kotlindev",
  "followerCount": 512,
  "isVerified": false,
  "bio": null,
  "profile": null,
  "joinedAt": "2022-11-03T09:15:00Z"
}
Output
import kotlinx.serialization.Serializable
import kotlinx.datetime.Instant

@Serializable
data class Profile(
    val dummy: String? = null
)

@Serializable
data class User(
    val userId: String,
    val username: String,
    val followerCount: Int,
    val isVerified: Boolean,
    val bio: String?,
    val profile: Profile?,
    val joinedAt: Instant
)

Related Tools