Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 341
ND_27 Avatar asked Aug 18 '14 01:08

ND_27


People also ask

What is the return type of ResponseEntity?

A ResponseEntity is returned. We give ResponseEntity a custom status code, headers, and a body. With @ResponseBody , only the body is returned. The headers and status code are provided by Spring.

How do you list responses in restTemplate?

3.2. Now we can use the simpler getForObject() method to get the list of employees: EmployeeList response = restTemplate. getForObject( "http://localhost:8080/employees", EmployeeList. class); List<Employee> employees = response.


1 Answers

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>>() {});
like image 193
Christophe L Avatar answered Oct 02 '22 16:10

Christophe L