Json2POJOJson2POJO

Kotlin JSON to Data Class: The Modern Way

Forget Java boilerplate. With Kotlin data classes, you get immutable, type-safe JSON mapping in one line. Learn kotlinx.serialization and Moshi.

Why Kotlin Data Classes Beat Java POJOs

Java POJO (50+ lines)

public class User {
    private String name;
    private int age;
    // getters...
    // setters...
    // equals...
    // hashCode...
    // toString...
}

Kotlin Data Class (1 line)

data class User(
    val name: String,
    val age: Int
)

Immutable by default. Auto-generated equals, hashCode, toString, copy().

Option 1: kotlinx.serialization (Official)

What is kotlinx.serialization? It's Kotlin's official serialization library by JetBrains. It uses compile-time code generation for maximum performance and type safety.

// 1. Add @Serializable annotation
@Serializable
data class User(
  val name: String,
  val age: Int
)

// 2. Parse JSON
val user = Json.decodeFromString<User>(jsonString)

Option 2: Moshi (Android Recommended)

Moshi by Square is the go-to JSON library for Android. It respects Kotlin null-safety and integrates seamlessly with Retrofit.

// Use @JsonClass for code generation (no reflection)
@JsonClass(generateAdapter = true)
data class User(
  @Json(name = "user_name") val name: String,
  val age: Int
)

// Parse JSON
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val adapter = moshi.adapter(User::class.java)
val user = adapter.fromJson(jsonString)

Kotlin Null Safety: The Game Changer

Why Gson fails with Kotlin: Gson uses unsafe Java reflection that bypasses Kotlin's null checks. A non-null String can become null at runtime, causing crashes.

val name: String = null // CRASH!

Gson can cause this

val name: String? = null // Safe

Moshi respects this

Default Values for Missing Fields

Unlike Java, Kotlin supports default parameter values. If a JSON field is missing, use the default:

data class User(
  val name: String,
  val age: Int = 0, // Default if missing
  val isActive: Boolean = true
)

Library Comparison

Featurekotlinx.serializationMoshiGson
Kotlin Null Safety✓ Full✓ Full✗ Unsafe
Default Values✓ SupportedRequires config✗ No
Android SizeMediumSmallSmall

Common Questions

Can I use Kotlin with Jackson?

Yes, add the jackson-module-kotlin dependency. It adds support for data classes and default values.

How to rename JSON fields?

Use @SerialName("field_name") for kotlinx.serialization or @Json(name = "field_name") for Moshi.

Generate Kotlin Data Classes Instantly

Our converter supports Kotlin output with @Serializable and Moshi annotations.

Convert JSON to Kotlin