I keep struggling with parsing response represented by a JSON array into a data class entity using Spring with Kotlin and RestTemplate. Non-array like responses are without an issue, ie. the following is just enough to work as expected:
// JSON response - parsed correctly { data: { items: [{foo: 1}, {foo: 2}]
data class SomeData(val items: List<Item>)
data class NonArrayDataClass(val data: SomeData)
return restTemplate.client.postForEntity(
url,
request,
NonArrayDataClass::class.java
)
} }
But if the response is directly an array, I do not know how to bind into the target entity, ie:
// JSON response - not parsed correctly { [ {foo: 1}, {foo: 2} ] }
data class SomeData(val items: List<Items>)
data class ArrayDataClass(val data: SomeData) // no *data* key inside response
return restTemplate.client.postForEntity(
url,
request,
// WHAT TO DO HERE? -> ArrayDataClass
)
A Data class (ArrayDataClass) cannot be directly a list/array and there is no root key inside the response (aka data) to bind the list to as in the first working example above, it is directly an array.