How to use the JSON to Kotlin
- Paste the JSON sample, such as a response from your backend.
- Set the root class name.
- Add default values to properties that may be missing (e.g. val rating: Double = 0.0).
- Copy the classes and decode with Json.decodeFromString<Root>(text).
Worked example
A book record
Input
{"id":3,"title":"Kotlin","published":true,"rating":4.5,"authors":["Ada"]}Kotlin
import kotlinx.serialization.Serializable
@Serializable
data class Root(
val id: Long,
val title: String,
val published: Boolean,
val rating: Double,
val authors: List<String>,
)Requires the kotlinx-serialization Gradle plugin and runtime library. Whole numbers map to Long so large IDs do not overflow.
Json configuration flags that matter
Set these when creating the decoder, e.g. val json = Json { ignoreUnknownKeys = true }.
| Flag | Default | Change it when |
|---|---|---|
| ignoreUnknownKeys | false | Set true if the API may add fields you have not modeled |
| coerceInputValues | false | Set true so null falls back to a non-null property's default |
| explicitNulls | true | Set false to omit null properties when encoding |
| isLenient | false | Set true for unquoted strings or keys (non-standard JSON) |
| encodeDefaults | false | Set true if defaults must be written out when encoding |
Missing keys and defaults
kotlinx.serialization treats a property without a default value as required: a missing key throws MissingFieldException. Give optional properties a default (val tags: List<String> = emptyList()) or make them nullable with a default (val bio: String? = null).
Names and Android
Use @SerialName("user_id") to keep a camelCase property while matching a snake_case key. On Android with R8 or ProGuard, Gson reflects over field names and can break after minification; kotlinx.serialization generates serializers at compile time and does not have that problem.
JSON to Kotlin FAQ
How do I parse JSON into a Kotlin data class?
With kotlinx.serialization: Json.decodeFromString<Root>(text). With Moshi: moshi.adapter(Root::class.java).fromJson(text). With Gson: Gson().fromJson(text, Root::class.java).
Why do I get "Encountered an unknown key" in Kotlin?
kotlinx.serialization rejects keys not declared in the class by default. Create the decoder with Json { ignoreUnknownKeys = true }.
Should a JSON property be nullable in Kotlin?
Make it nullable if the API can send null. If the key can be missing, also give it a default value, otherwise decoding fails.
Does Gson respect Kotlin default values?
Not reliably. Gson creates objects without calling the Kotlin constructor, so missing fields can end up null even when declared non-null. Prefer kotlinx.serialization or Moshi with codegen.
Can I use these classes with Retrofit?
Yes. Add the kotlinx.serialization converter (or the Moshi/Gson one) to your Retrofit builder and use the generated classes as return types.

