Reputation: 774
My REST client uses RestTemplate to obtain a List of objects.
ResponseEntitiy<List> res = restTemplate.postForEntity(getUrl(), myDTO, List.class);
Now I want to use the list returned and return it as List to the calling class. In case of string, toString could be used, but what is the work around for lists?
Upvotes: 20
Views: 101486
Reputation: 342
From here: https://www.baeldung.com/spring-rest-template-list
ResponseEntity<Team[]> response = this.restTemplate.getForEntity(
this.API_URL(), Team[].class);
Upvotes: 0
Reputation:
You can use the ParameterizedTypeReference class of Spring to convert to List the data returned by ResponseEntity
ResponseEntity<List<MyObject>> resp = restTemplate.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<MyObject>>(){});
if(resp != null && resp.hasBody()){
List<MyObject> myList = resp.getBody();
}
Upvotes: 3
Reputation: 1209
You have unwrap the ResponseEntity and you can get the object(list)
res.getBody()
Upvotes: 0
Reputation: 1026
In the latest version (Spring Framework 5.1.6) both the answers are not working.
As kaybee99 mentioned in his answer postForEntity
method signature got changed.
Also the restTemplate.exchange()
method and its overloads need a RequestEntity<T>
or its parent HttpEntity<T>
object. Unable to pass my DTO object as mentioned.
Here is the code which worked for me
List<Shinobi> shinobis = new ArrayList<>();
shinobis.add(new Shinobi(1, "Naruto", "Uzumaki"));
shinobis.add(new Shinobi(2, "Sasuke", "Uchiha");
RequestEntity<List<Shinobi>> request = RequestEntity
.post(new URI(getUrl()))
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(shinobis);
ResponseEntity<List<Shinobi>> response = restTemplate.exchange(
getUrl(),
HttpMethod.POST,
request,
new ParameterizedTypeReference<List<Shinobi>>() {}
);
List<Shinobi> result = response.getBody();
Hope it helps someone.
Upvotes: 11
Reputation: 4744
I couldn't get the accepted answer to work. It seems postForEntity
no longer has this method signature. I had to use restTemplate.exchange()
instead:
ResponseEntity<List<MyObj>> res = restTemplate.exchange(getUrl(), HttpMethod.POST, myDTO, new ParameterizedTypeReference<List<MyObj>>() {});
Then to return the list, as above:
return res.getBody();
Upvotes: 18
Reputation: 14035
First off, if you know the type of elements in your List, you may want to use the ParameterizedTypeReference
class like so.
ResponseEntity<List<MyObj>> res = restTemplate.postForEntity(getUrl(), myDTO, new ParameterizedTypeReference<List<MyObj>>() {});
Then if you just want to return the list you can do:
return res.getBody();
And if all you care about is the list, you can just do:
// postForEntity returns a ResponseEntity, postForObject returns the body directly.
return restTemplate.postForObject(getUrl(), myDTO, new ParameterizedTypeReference<List<MyObj>>() {});
Upvotes: 33