About the JSON to Kotlin
Generate Kotlin data classes from JSON for kotlinx.serialization, Gson or Moshi, with the right annotations for renamed keys and nullable defaults for optional fields.
Key features
- Kotlin data classes from any JSON sample
- kotlinx.serialization, Gson or Moshi annotations
- camelCase properties with @SerialName / @SerializedName / @Json
- Nullable types with = null defaults
- Int vs Long chosen from your values
- Kotlin keywords escaped with backticks
Kotlin data classes from JSON
Android apps, Ktor servers and Kotlin Multiplatform projects all parse JSON into data classes. Generate them from a real response, with the annotations your serialization library expects.
Example
{ "user_id": 7, "name": "Ada", "nickname": null, "roles": ["admin"] }
@Serializable
data class Root(
@SerialName("user_id") val userId: Int,
val name: String,
val nickname: JsonElement? = null,
val roles: List<String>,
)
val root = Json.decodeFromString<Root>(json)
Library annotations
| Library | Class annotation | Renamed key |
|---|---|---|
| kotlinx.serialization | @Serializable | @SerialName("user_id") |
| Moshi (codegen) | @JsonClass(generateAdapter = true) | @Json(name = "user_id") |
| Gson | — | @SerializedName("user_id") |
Tips
- kotlinx.serialization: apply the
plugin.serializationGradle plugin; useJson { ignoreUnknownKeys = true }for evolving APIs. - Retrofit: pair Moshi or kotlinx with the matching converter factory.
- Dates: replace strings with
Instantplus a custom serializer.
Related tools
Building the iOS app too? Use JSON to Swift. For Java code, see JSON to Java.
How to use the JSON to Kotlin
- Paste your data into the input box, upload a file, or click Sample to try it out.
- Adjust the options above the editor if you need to (indentation, delimiter, and so on).
- The Kotlin appears instantly in the output panel. Any errors are shown with their line and column.
- Click Copy to copy the result, or Download to save it as a file.