How to Generate Kotlin Data Classes from JSON
Working with JSON in Kotlin usually means @Serializable data classes from kotlinx.serialization. Generating them from a sample gets the property names, annotations, and nullability right automatically. Here's how the output is built.
From JSON to data classes
Each JSON object becomes a data class, nested objects become their own classes, and every class is annotated @Serializable:
{ "id": 1, "user_name": "Ada" }
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
data class Root(
val id: Int,
@SerialName("user_name") val userName: String,
)
The @Serializable annotation is what lets Json.encodeToString and decodeFromString round-trip the class to your exact JSON.
Property names and @SerialName
Kotlin convention is camelCase properties. When a JSON key uses another style — user_name, first-name — the property is camel-cased and a @SerialName annotation preserves the original key so serialization stays exact:
@SerialName("user_name") val userName: String,
Properties that collide with Kotlin keywords are wrapped in backticks so they stay valid.
Nullable properties and defaults
When you convert an array of objects and a key is missing from some elements, the property becomes nullable with a default of null:
val views: Int? = null,
The default means the property can be omitted entirely when decoding. Arrays map to List<T>, whole numbers become Int (or Long when they overflow) and decimals Double, and a null or unknown type falls back to JsonElement.
Related
Generating types for another language? See JSON to Java and JSON to Rust.
Try it
Paste a JSON response and get Kotlin data classes instantly — everything runs in your browser, nothing uploaded.