Skip to main content
Back to tools

JSON to Kotlin Data Class

Generate kotlinx.serialization data classes from a JSON object

About JSON to Kotlin Data Class

Builds @Serializable data classes for kotlinx.serialization, with camelCase properties and @SerialName where the Kotlin name differs from the key. Whole numbers become Long, decimals Double, nulls and keys missing from some array items nullable with a null default, and mixed or empty values use JsonElement. Types come from one sample, so review them before adding the models to an Android or Ktor project; everything runs client-side.

Category: Converters.

Frequently asked questions

Which dependencies does the generated Kotlin code need?

▾

The kotlinx-serialization-json library plus the Kotlin serialization compiler plugin (org.jetbrains.kotlin.plugin.serialization in Gradle). Without the plugin the classes still compile, but Json can't find a serializer for them at runtime.

Why are whole numbers typed as Long instead of Int?

▾

IDs and millisecond timestamps often exceed the Int limit of 2,147,483,647, and Long holds any whole number up to 2^63, so decoding won't overflow. Switch to Int where values are small, and to Double where a field written as 1.0 in the sample can also hold fractions.

How do I decode JSON into the generated classes?

▾

Call Json.decodeFromString<Root>(text), or Json.decodeFromString<RootList>(text) when the JSON is a top-level array. The default Json rejects keys that aren't in the class, so use Json { ignoreUnknownKeys = true } if the API may add fields.

How are keys like my-key, class or 2fa handled?

▾

They become valid property names and keep the original key in @SerialName, so my-key turns into myKey and 2fa into _2fa. Kotlin keywords such as class or in are wrapped in backticks, and names that collide after conversion get a numeric suffix.

Related tools