JSON to Kotlin Data Class Converter

Generate Kotlin data classes from JSON, with toJson and fromJson helpers.

Generate Kotlin data classes from JSON

Kotlin data classes are the natural model type for JSON on Android and the JVM. This converter produces one data class per object with immutable val properties: whole numbers become Long, decimals Double, arrays List<T> and nested objects their own data class. The generated code uses the Klaxon library and adds a toJson method and a companion fromJson function, so a single call turns a JSON string into a typed object.

How to use

  1. Paste a JSON sample, for example the response your Android app receives.
  2. Enter the root class name, for example Movie.
  3. Add the Klaxon dependency, paste the classes into a .kt file in your package, and call Movie.fromJson(jsonString).

Frequently asked questions

Can I use these classes with kotlinx.serialization, Moshi or Gson?
Yes. The data class declarations are plain Kotlin. Remove the Klaxon helpers and add your library's annotation, such as @Serializable for kotlinx.serialization, to each class.
How are nullable fields generated?
Fields that are null or missing in part of the sample become nullable types such as String?, so Kotlin's null safety makes you handle them.
Why Long instead of Int?
JSON integers have no size limit, so Long avoids overflow. Change a property to Int if you know the values are small, for example a year or a count.

Example: JSON to Kotlin

Input JSON

{
  "id": 12,
  "title": "Arrival",
  "year": 2016,
  "genres": ["sci-fi", "drama"],
  "rating": 7.9
}

Generated Kotlin (Movie)

// To parse the JSON, install Klaxon and do:
//
//   val movie = Movie.fromJson(jsonString)

package quicktype

import com.beust.klaxon.*

private val klaxon = Klaxon()

data class Movie (
    val id: Long,
    val title: String,
    val year: Long,
    val genres: List<String>,
    val rating: Double
) {
    public fun toJson() = klaxon.toJsonString(this)

    companion object {
        public fun fromJson(json: String) = klaxon.parse<Movie>(json)
    }
}

Convert JSON to other languages