Skip to content
Devtoolry

JSON to Kotlin

Convert JSON to Kotlin data classes online, with kotlinx.serialization @Serializable and @SerialName annotations and nullable types for missing keys.

Something not working, or missing a feature? Send feedback

About the JSON to Kotlin

The JSON to Kotlin converter generates Kotlin data classes from a JSON sample, annotated for kotlinx.serialization by default. Keys become camelCase properties with @SerialName where they differ, arrays become List<T>, and keys missing from some items become nullable with a default of null.

Conversion happens in your browser, so your files and records stay private.

How to use the JSON to Kotlin

  1. Paste a JSON sample and set the root class name.
  2. Choose kotlinx.serialization annotations or plain data classes.
  3. Copy the code and decode with Json.decodeFromString<User>(text).

Example

Kotlin data classes for kotlinx.serialization

Input

{
  "id": 7,
  "fullName": "Grace Hopper",
  "email": null,
  "roles": ["admin"],
  "team": { "name": "Compilers", "size": 4 },
  "projects": [
    { "name": "COBOL", "year": 1959 },
    { "name": "A-0", "year": 1952, "archived": true }
  ]
}

Result

import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonElement

@Serializable
data class User(
    val id: Long,
    val fullName: String,
    val email: JsonElement?,
    val roles: List<String>,
    val team: Team,
    val projects: List<Project>,
)

@Serializable
data class Project(
    val name: String,
    val year: Long,
    val archived: Boolean? = null,
)

@Serializable
data class Team(
    val name: String,
    val size: Long,
)

Optional keys default to null, so decoding works when they are missing. Unknown values (email was only null) use JsonElement.

Common mistakes

  • Missing keys without defaults. kotlinx.serialization throws MissingFieldException when a non-optional property is absent. Keep = null on properties that can be missing.
  • Unknown keys in the input. By default, extra keys in the JSON cause an error. Decode with Json { ignoreUnknownKeys = true } when the API may add fields.

Works well with the JSON to Kotlin

Frequently asked questions

Does it work with Moshi or Gson?

Choose None for plain data classes, then add @Json(name = …) for Moshi or @SerializedName for Gson where the property name differs from the key.

Why do optional properties default to null?

kotlinx.serialization fails when a non-optional property is missing from the input. A default value makes the property optional, so data without that key still decodes.

What is JsonElement?

A kotlinx.serialization type for any JSON value. It is used where the sample did not show a single type, for example a value that was only ever null.