Return the List<myObj> returned by ResponseEntity<List>

ND_27 picture ND_27 · Aug 18, 2014 · Viewed 50.7k times · Source

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?

Answer

Christophe L picture Christophe L · Aug 18, 2014

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>>() {});