0

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.

David Zaba
  • 67
  • 1
  • 9
  • 1
    try `restTemplate.postForEntity(..., Array::class.java)` https://stackoverflow.com/questions/39679180/kotlin-call-java-method-with-classt-argument – Marc Stroebel Aug 21 '23 at 11:19
  • Would there be an elegant solution for Map as well? Currently restTemplate/IDE complains with "Only classes are allowed on the left hand side of a class literal". – David Zaba Aug 24 '23 at 08:51
  • perhaps this works... `restTemplate.exchange(..., object: ParameterizedTypeReference> () {})` https://stackoverflow.com/questions/52581729/create-instance-of-spring%C2%B4s-parameterizedtypereference-in-kotlin – Marc Stroebel Aug 25 '23 at 16:24

1 Answers1

0

If you are completely sure about content in response, you can just write this:

val itemList = RestTemplate().postForEntity(
        url,
        request,
        List::class.java
    ).body as List<Item>

p.s. Your second json

{[{"foo":1},{"foo":2}]}

is not valid json:). Only your first one, or this

{"items":[{"foo":1},{"foo":2}]}

or this (code I suggested is suitable for this example)

[{"foo":1},{"foo":2}]

alexzoop
  • 1
  • 2