Return the List<myObj> returned by ResponseEntity<List>
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>>() {});
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();
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.
Checkout the documentation of the RestTemplate class
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.