Convert Dynamic JSON Keys to Kotlin Map Types
Learn how to handle JSON objects with dynamic or unknown keys using Kotlin Map types. Covers Map<String, T>, mixed-value maps, and iteration patterns.
Detailed Explanation
Dynamic JSON Keys with Kotlin Maps
When a JSON object has keys that are not known at compile time, you cannot define a data class with fixed properties. Instead, use Kotlin's Map<String, T> type.
Example JSON
{
"metrics": {
"cpu_usage": 72.5,
"memory_usage": 85.3,
"disk_io": 45.1
},
"labels": {
"env": "production",
"region": "us-east-1"
}
}
Generated Kotlin
data class Dashboard(
val metrics: Map<String, Double>,
val labels: Map<String, String>
)
Mixed Value Types
When values have different types, use Map<String, Any> or Map<String, JsonElement> with kotlinx.serialization:
{
"settings": {
"theme": "dark",
"fontSize": 14,
"autoSave": true
}
}
data class Config(
val settings: Map<String, JsonElement>
)
Accessing Map Values
val cpuUsage = dashboard.metrics["cpu_usage"] // Double?
val env = dashboard.labels["env"] ?: "unknown"
// Iterate over all entries
dashboard.metrics.forEach { (key, value) ->
println("$key: $value")
}
Map vs Data Class Decision
Use a data class when:
- Keys are known and fixed
- You want compile-time property access
Use a Map when:
- Keys are dynamic, user-defined, or vary between responses
- The object acts as a key-value store
Nested Maps
data class Config(
val sections: Map<String, Map<String, String>>
)
This handles JSON structures like { "database": { "host": "...", "port": "..." }, "cache": { ... } } where both levels have dynamic keys.
Use Case
Monitoring dashboards, feature flag systems, and key-value stores return JSON with unpredictable keys. Kotlin maps let you process these flexibly without needing to know exact key names at compile time.
Try It — JSON to Kotlin
Related Topics
Convert JSON Arrays to Kotlin Lists
Collections
Convert Simple JSON to a Kotlin Data Class
Basic Data Classes
Use Kotlin Generics for Reusable JSON Response Wrappers
Advanced Patterns
Model a REST API Response in Kotlin Data Classes
Real-World Patterns
Configure JSON Naming Strategy in Kotlin Serialization
Serialization