JSON to Kotlin data class generator
Paste a JSON response and get Kotlin data classes for it. Plain classes suit Gson, Moshi or Jackson; the kotlinx.serialization option adds @Serializable to each class and @SerialName where a key is not a camelCase name.
Runs in your browser: nothing you enter is sent anywhere.
How to use it
- Paste a JSON sample, ideally with several items in each array so optional keys are found.
- Choose plain data classes or kotlinx.serialization annotations.
- Copy the code into a .kt file and rename Root and the other classes to fit your domain.
How it works
The sample is read into a shape: every key with every type seen there, and all objects of an array merged into one class.
- Class names come from keys: items holds a List
- , line_items a List. Root is first.
- Properties are val, one per line, with a trailing comma (Kotlin 1.4+).
- With kotlinx.serialization, imports cover Serializable, SerialName and JsonElement only when used.
- A top-level array gives a typealias, such as typealias Root = List.
Worked example
{"line_items":[{"sku":"A","note":null,"qty":1},{"sku":"B","note":"x"}]} with kotlinx.serialization gives:
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Root(
@SerialName("line_items")
val lineItems: List<LineItem>,
)
@Serializable
data class LineItem(
val sku: String,
val note: String?,
val qty: Long? = null,
)
Tips
- Decode with
Json.decodeFromString<Root>(text); add Json { ignoreUnknownKeys = true } if the real data has more keys than the sample.
- Change Long to Int where values are known to be small.
- For Android projects using Gson, pick Plain and replace the comments with @SerializedName.
Frequently asked questions
How are JSON types mapped to Kotlin?
Strings become String, true and false Boolean, whole numbers Long and other numbers Double (a mix of both becomes Double). Arrays become List<T> and objects their own data classes. A place holding different kinds of values becomes Any? in plain mode and JsonElement? with kotlinx.serialization.
What is the difference between String? and String? = null?
A value that is null in the sample is String?: the key must be present, but may be null. A key missing from some objects of an array gets String? = null, so decoding works when the key is absent; kotlinx.serialization needs the default for that.
What happens to keys like order_id or in?
Property names are camelCase: order_id becomes orderId. With kotlinx.serialization the original key goes into @SerialName("order_id"); in plain mode a comment keeps it, and you can add your library's annotation (@SerializedName for Gson, @Json for Moshi). A Kotlin keyword such as in is written in backticks.
Why does an empty object become a plain class?
A data class needs at least one property in its constructor, so an object without keys becomes class Meta (or @Serializable class Meta).