javarestspring-mvcrestful-architectureresttemplate

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?


Solution

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