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.
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:
- Flatten where possible -- create helper extension functions that expose deeply nested values at a higher level.
- Use meaningful names -- rename generated classes to reflect domain concepts (e.g.,
ShippingAddressinstead ofAddress). - 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
Related Topics
Convert Simple JSON to a Kotlin Data Class
Basic Data Classes
Convert JSON Arrays to Kotlin Lists
Collections
Handle Nullable JSON Fields in Kotlin Data Classes
Basic Data Classes
Model Polymorphic JSON with Kotlin Sealed Classes
Advanced Patterns
Model a REST API Response in Kotlin Data Classes
Real-World Patterns