Convert Nested JSON Objects to Kotlin Data Classes

Learn how to convert nested JSON objects into separate Kotlin data classes. Covers parent-child relationships, naming conventions, and deep nesting strategies.

Basic Data Classes

Detailed Explanation

Handling Nested JSON in Kotlin

Real-world JSON almost always contains nested objects. In Kotlin, each nested object becomes its own data class, and the parent holds a property of that type.

Example JSON

{
  "user": {
    "name": "Bob",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "Springfield",
      "zip": "62704"
    }
  }
}

Generated Kotlin

data class Root(
    val user: User
)

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

data class Address(
    val street: String,
    val city: String,
    val zip: String
)

How Nesting Works

Each nested JSON object requires a separate data class in Kotlin. The converter generates a distinct class for every nesting level, naming it after the parent key in PascalCase. If two different objects share the same key name, the converter qualifies the name (e.g., UserAddress vs CompanyAddress).

Accessing Nested Data

val root = Json.decodeFromString<Root>(jsonString)
println(root.user.address.city) // "Springfield"

Deep Nesting Considerations

For deeply nested JSON (4+ levels), consider:

  1. Flatten where possible -- create helper extension functions that expose deeply nested values at a higher level.
  2. Use meaningful names -- rename generated classes to reflect domain concepts (e.g., ShippingAddress instead of Address).
  3. Separate files -- place each data class in its own file for large models.

Sealed Class Alternative

When nested objects represent variants (e.g., different payment methods), consider using Kotlin sealed classes instead of plain data classes for better type safety.

Use Case

APIs from services like Stripe, GitHub, and Twilio frequently return deeply nested JSON responses. Converting these to nested Kotlin data classes allows safe traversal with compile-time type checking on Android and Kotlin server applications.

Try It — JSON to Kotlin

Open full tool