JSON to Kotlin data class

Useful for Android apps and Ktor servers: it writes a data class per object, ready for Json.decodeFromString.

Loading the tool…

Processing and privacy: The result is calculated inside your browser and your data is not sent to any server.

How to use it

  1. Enter json input and root type name.
  2. The result appears straight away and updates as you edit.
  3. Copy the result, or copy a link that keeps the same values to share it.

How it is calculated

String, Int or Long, Double, Boolean, List<T> and JsonElement, with an @Serializable data class per object. @SerialName is added when a name differs from the key, null makes the type nullable, and a key missing from some items defaults to null.

Example

Inputs: Root type name = Root. Result: Generated code: import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Root( val id: Int, val name: String, val email: String, @SerialName("is_active") val isActive: Boolean, val balance: Double, val tags: List<String>, val address: Address, val orders: List<Order>, ) @Serializable data class Address( val city: String, @SerialName("postal_code") val postalCode: String, ) @Serializable data class Order( @SerialName("order_id") val orderId: String, val total: Double, val coupon: String?, ); Types generated: 3; Fields: 13.

{
  "id": 1024,
  "name": "Sara Ahmed",
  "email": "sara@example.com",
  "is_active": true,
  "balance": 1520.75,
  "tags": ["vip", "riyadh"],
  "address": { "city": "Riyadh", "postal_code": "12211" },
  "orders": [
    { "order_id": "A-1", "total": 99.5, "coupon": "EID10" },
    { "order_id": "A-2", "total": 120, "coupon": null }
  ]
}
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class Root(
    val id: Int,
    val name: String,
    val email: String,
    @SerialName("is_active")
    val isActive: Boolean,
    val balance: Double,
    val tags: List<String>,
    val address: Address,
    val orders: List<Order>,
)

@Serializable
data class Address(
    val city: String,
    @SerialName("postal_code")
    val postalCode: String,
)

@Serializable
data class Order(
    @SerialName("order_id")
    val orderId: String,
    val total: Double,
    val coupon: String?,
)

Limits and caveats

  • Needs kotlinx.serialization (the compiler plugin and the json library) in your project.
  • With Gson or Moshi, replace @SerialName with that library's annotation.

Questions about this tool

Why do some fields have = null?

kotlinx.serialization rejects a missing key unless it has a default, so keys missing from some items default to null.

When is Long used instead of Int?

When the sample holds a number above 2147483647, the upper limit of Int.

Is my JSON sent to a server?

No. The conversion runs in your browser and the JSON never leaves your device.