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?
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.
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.
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>>() {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With