JSON to Kotlin

Infer Kotlin data classes from a JSON sample.

About JSON to Kotlin

Generate Kotlin data classes for kotlinx.serialization from a JSON sample. Paste JSON and @Serializable classes appear as you type, one per nested object.

How to use

  1. Paste JSON, or load a .json file (up to 5 MB).
  2. Optionally change the root class name (default Root). It must start with a letter or underscore and contain only letters, digits and underscores.
  3. The Kotlin code updates as you type. Copy it, or Download it as a .kt file. The output needs the kotlinx.serialization plugin and runtime.

What it does

JSON Kotlin
string String
integer Long
other number Double
boolean Boolean
null, or mixed types JsonElement
array List<T>
nested object a named data class, RootAddress
null in some items T?
key missing from some items T? = null
  • Property names are camelCase; a key that differs, such as first_name, keeps the original in @SerialName("first_name"). Keywords such as when are written in backticks.
  • Nested data classes are listed before the class that uses them. An empty object becomes a plain @Serializable class, because a data class needs at least one property.
  • Imports cover only what the classes use: Serializable, and SerialName or JsonElement when they appear.

Example

{ "id": 1, "user_name": "Ada", "tags": ["admin"] }
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class Root(
    val id: Long,
    @SerialName("user_name")
    val userName: String,
    val tags: List<String>
)

Privacy

Inference runs in the page. No request is made and nothing is stored.

Frequently asked questions

How do I parse JSON in Kotlin with kotlinx.serialization?
Mark the class @Serializable, apply the kotlinx.serialization Gradle plugin, and call Json.decodeFromString<Root>(text). Use Json { ignoreUnknownKeys = true } when the payload may carry keys the class does not declare.
What does @SerialName do?
It sets the JSON key for a property when it should differ from the Kotlin name, for example @SerialName("user_name") val userName. Without it, the serialiser uses the property name as the key.
Why do optional properties need a default value?
kotlinx.serialization treats a property without a default as required and fails when the key is missing. Giving it = null makes the key optional, and the nullable type lets an explicit null through as well.
Should I use Int or Long for JSON numbers?
Long is the safer default: IDs and timestamps often exceed the Int range of about 2.1 billion. Switch to Int when you know the field is small, or to Double when the sample shows a fraction.