JSON to Kotlin data class converter

Paste JSON and get Kotlin data classes with the annotations of kotlinx.serialization, Moshi or Gson. Keys missing or null in any array item become nullable, and a default-values option controls what happens when the API leaves a field out.

Updated

Nested classes are named from their keys: orders becomes Order.

A default lets decoding succeed when the key is absent. Nested class properties never get one.

Kotlin data classes

3 classes, 14 properties

kotlinx.serialization

Kotlin data classes

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class User(
    val id: Int,
    @SerialName("first_name") val firstName: String,
    @SerialName("is_active") val isActive: Boolean,
    val balance: Double,
    @SerialName("created_at") val createdAt: String,
    val address: Address,
    val tags: List<String>,
    val orders: List<Order>,
)

@Serializable
data class Address(
    val city: String,
    @SerialName("pin_code") val pinCode: String,
)

@Serializable
data class Order(
    @SerialName("order_id") val orderId: Int,
    val total: Double,
    val coupon: String? = null,
    val note: String? = null,
)

// Usage:
// val json = Json { ignoreUnknownKeys = true }
// val data = json.decodeFromString<User>(source)
// val text = json.encodeToString(data)
  • Setup: apply the plugin kotlin("plugin.serialization") (same version as Kotlin) and add org.jetbrains.kotlinx:kotlinx-serialization-json; its GitHub releases listed 1.12.0 as latest on 2026-11-11.
  • kotlinx.serialization only accepts a missing key when the property has a default, which is why every nullable property here ends in = null. Add ignoreUnknownKeys = true if the API returns keys you don't model.
  • Some strings look like ISO 8601 dates. They are String here: kotlinx.serialization has no Instant serializer in the core library, and Moshi and Gson need an adapter. Parse with java.time.Instant.parse(...) where you use them.

How are Kotlin data classes worked out from JSON?

Every JSON object becomes a data class with val properties, and a list becomes List<T> where T is inferred from all the items together. A key that is missing from some items, or null in some, becomes a nullable property (String?). A number is Int, becomes Long when a value does not fit in 32 bits, and becomes Double when any value has a decimal part.

The three libraries disagree about what happens when a key is absent, and that decides which output is safe. kotlinx.serialization needs a default value for a property to be allowed to go missing, so nullable properties get = null. Moshi's generated adapter respects Kotlin's types and throws JsonDataException for a missing non-null property. Gson ignores Kotlin's null safety entirely and fills the field with null, so a non-null String can still hold null.

Property names are lowerCamelCase, so first_name becomes firstName and the library annotation (@SerialName, @Json(name = ...) or @SerializedName) keeps the original key. Kotlin hard keywords such as class, in and object can't be property names without backticks, so those are renamed with a Value suffix and annotated.

The default-values option matters most for kotlinx.serialization and Moshi. Choosing a default for every property lets decoding survive a missing key, at the cost of hiding a malformed response behind an empty string or 0, so use it for optional data and leave identifiers without defaults.

{"n": 5}, {"n": 5000000000} -> Long n
{"n": 1}, {"n": 1.5}        -> Double n
{"n": 1}, {}  or  {"n": null} -> Int? n = null

How do the three Kotlin JSON libraries compare?

Annotations and behaviour for each library, as generated by this page
kotlinx.serializationMoshi (codegen)Gson
Class annotation@Serializable@JsonClass(generateAdapter = true)none
Rename a key@SerialName("key")@Json(name = "key")@SerializedName("key")
Missing key, non-null propertySerializationException unless it has a defaultJsonDataException unless it has a defaultField is silently null
Missing key, nullable propertyError unless = nullnullnull
How it worksCompiler plugin, no reflectionKSP / kapt generated adapterReflection at runtime
Untyped valueJsonElementAnyAny
MultiplatformYes (JVM, JS, Native)JVM / AndroidJVM / Android

How to turn JSON into Kotlin data classes

  1. 1
    Paste the JSONUse a real response. For lists, include several items so keys that come and go are seen. Errors name the line and column.
  2. 2
    Choose the libraryPick the one your project already uses. kotlinx.serialization suits Kotlin Multiplatform and Ktor, Moshi is common with Retrofit, Gson in older Android code.
  3. 3
    Set the default valuesKeep = null on nullable properties. Add defaults to every property only when the API genuinely omits fields.
  4. 4
    Copy the classes and decodePaste into a .kt file, add the plugin or dependency from the notes, then use the decode line at the end. Check any Any or JsonElement properties.

Frequently asked questions

Why does kotlinx.serialization fail with “Field is required but it was missing”?
A property without a default value is required. Make it nullable with = null, give it a default, or the key must always be present. This page adds = null to every nullable property for that reason.
Should I use Int or Long for ids from an API?
Use Long when ids can exceed 2,147,483,647, which database ids often do. This page picks Long when any sample value is beyond the Int range, but a short sample may not show it, so check your API's id type.
What is the difference between a nullable property and a default value?
Nullable (String?) means the value may be null. A default (= "") means the key may be absent. They are separate: a key can be absent with no default if the property is nullable and the library fills in null, as Moshi and Gson do. kotlinx.serialization wants the = null written out.
Does Moshi need the KotlinJsonAdapterFactory?
Not for classes annotated @JsonClass(generateAdapter = true), because the KSP or kapt step generates their adapters. The reflection factory is the alternative that avoids codegen, at the cost of kotlin-reflect and slower startup.
Why are my Gson fields null when the property is not nullable?
Gson creates the object without calling a Kotlin constructor that has required parameters and sets fields by reflection, so Kotlin's null checks never run. A missing key leaves null in a String property that the compiler believes is never null. Prefer Moshi or kotlinx.serialization if you want that protection.
How do I decode a list at the top level?
With kotlinx.serialization use decodeFromString<List<User>>(source). Moshi needs Types.newParameterizedType(List::class.java, User::class.java), and Gson needs a TypeToken, because generics are erased on the JVM. The example at the end of the output writes the right form.

Sources

Related tools

See all 135 free tools

Need a custom dev tool for your team?

We build internal tools, dashboards, APIs, and SaaS platforms. If you can describe it, we can ship it.

Built by CountryDevs · No signup · No ads · We count visits, never what you enter