JSON to Kotlin
Generate Kotlin data class declarations from a JSON sample. Choose kotlinx.serialization or Moshi; keys that differ from the Kotlin property name get @SerialName or @Json(name = …), and optional fields become nullable with an optional = null default.
How to generate Kotlin data classes from JSON
- Paste a JSON sample — ideally an array of several records, so optional fields are detected.
- Set the Root type name. Nested objects are named after the key that holds them, singularised for arrays.
- Pick your serialization library — kotlinx.serialization for multiplatform and modern Android, Moshi for existing Retrofit stacks.
- Leave = null defaults on so a missing key deserialises instead of throwing.
- Copy the code, or download it as a file.
Type mapping
- Integers →
Long; fractional →Double; booleans →Boolean; strings →String. - Arrays →
List<T>. - Objects → a nested data class.
- null / mixed →
JsonElementwith kotlinx,Anywith Moshi.
Getting good types out of a sample
Type inference from a sample is only as good as the sample. Three habits make the output far more useful:
- Paste an array, not one record. When you pass several records, a key missing from any of them is marked optional and a field that is sometimes a number and sometimes a float widens to a float. One record makes everything look required.
- Include the awkward cases. A record with a null, an empty array, and a missing optional key teaches the generator more than ten identical happy-path records.
- Check unions by hand. A field that holds different shapes in different records falls back to the language's "any" type. That is a signal your data has a variant the generator cannot express — model it explicitly.
Privacy
Nothing is uploaded. Inference and code generation run in this tab. No server sees the payload you paste — which matters, because real API responses tend to contain real user data.
FAQ
Why does a default value matter?
With kotlinx.serialization, a non-nullable property with no default throws MissingFieldException when the key is absent. A = null default on a nullable property makes the field genuinely optional, which is what most APIs mean.
Do I need the serialization plugin?
For kotlinx.serialization, yes — add the plugin.serialization Gradle plugin and the kotlinx-serialization-json dependency. Moshi needs moshi-kotlin-codegen via KSP for @JsonClass(generateAdapter = true) to work.
Are the classes multiplatform-safe?
The generated code uses only stdlib types, so yes with kotlinx.serialization. Moshi is JVM-only.