Convert JSON Arrays to Kotlin Lists
Learn how JSON arrays map to Kotlin List types. Covers primitive lists, lists of objects, nested arrays, and empty array handling with practical Kotlin examples.
Detailed Explanation
JSON Arrays to Kotlin Lists
JSON arrays map to Kotlin's List<T> type. The element type is inferred from the array contents -- string arrays become List<String>, object arrays become List<SomeDataClass>.
Primitive Arrays
{
"tags": ["kotlin", "android", "api"],
"scores": [95, 87, 92]
}
data class Response(
val tags: List<String>,
val scores: List<Int>
)
Array of Objects
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}
data class Response(
val users: List<User>
)
data class User(
val id: Int,
val name: String
)
Empty Arrays
Empty JSON arrays ([]) are ambiguous -- the converter cannot determine the element type. Most converters default to List<Any>. You should manually set the correct type once you know the expected data.
Nested Arrays
Arrays of arrays ([[1,2],[3,4]]) become List<List<Int>> in Kotlin. This pattern appears in matrix data, coordinate pairs, and batch operations.
List vs MutableList
The converter generates List<T> (immutable) by default. If you need to modify the collection after deserialization, change it to MutableList<T>:
data class Response(
val users: MutableList<User>
)
Iterating Over Results
response.users.forEach { user ->
println("User ${user.id}: ${user.name}")
}
// Or with destructuring
response.users.forEach { (id, name) ->
println("User $id: $name")
}
Kotlin's destructuring works with data classes automatically, making list iteration concise and readable.
Use Case
Paginated API responses, list endpoints, and bulk operations all return arrays of objects. Converting these to typed Kotlin lists enables safe iteration with full IDE support in Android RecyclerView adapters and Kotlin server handlers.
Try It — JSON to Kotlin
Related Topics
Convert Simple JSON to a Kotlin Data Class
Basic Data Classes
Convert Nested JSON Objects to Kotlin Data Classes
Basic Data Classes
Convert Dynamic JSON Keys to Kotlin Map Types
Collections
Handle Nullable JSON Fields in Kotlin Data Classes
Basic Data Classes
Model a REST API Response in Kotlin Data Classes
Real-World Patterns