I want to use Spring RestTemplate
in Kotlin like this:
//import org.springframework.web.client.RestTemplate
fun findAllUsers(): List {
I think you need to actually use the RestTemplate.exechange
method that has a signature that accepts a ParameterizedTypeReference
where T
can be the generic type of your response (in your case a List
)
Suppose I have an endpoint that returns a list of Jedi names in JSON format, as follows
["Obi-wan","Luke","Anakin"]
And I would like to invoke this endpoint and get a List
as the result, with the list containing the Jedi names from the JSON.
Then I can do this:
val endpoint = URI.create("http://127.0.0.1:8888/jedi.json")
val request = RequestEntity(HttpMethod.GET, endpoint)
val respType = object: ParameterizedTypeReference>(){}
val response = restTemplate.exchange(request, respType)
val items: List = response.body;
println(items) //prints [Obi-wan, Luke, Anakin]
Notice that my ParameterizedTypeReference
has a type argument of List
. That's what does the trick.
And that worked for me when I tried it.