If you would prefer a List of POJOs, one way to do it is like this:
class SomeObject {
private int id;
private String name;
}
public <T> List<T> getApi(final String path, final HttpMethod method) {
final RestTemplate restTemplate = new RestTemplate();
final ResponseEntity<List<T>> response = restTemplate.exchange(
path,
method,
null,
new ParameterizedTypeReference<List<T>>(){});
List<T> list = response.getBody();
return list;
}
And use it like so:
List<SomeObject> list = someService.getApi("http://localhost:8080/some/api",HttpMethod.GET);
Explanation for the above can be found here (https://www.baeldung.com/spring-rest-template-list) and is paraphrased below.
There are a couple of things happening in the code above. First, we use ResponseEntity as our return type, using it to wrap the list of objects we really want. Second, we are calling RestTemplate.exchange() instead of getForObject().
This is the most generic way to use RestTemplate. It requires us to specify the HTTP method, optional request body, and a response type. In this case, we use an anonymous subclass of ParameterizedTypeReference for the response type.
This last part is what allows us to convert the JSON response into a list of objects that are the appropriate type. When we create an anonymous subclass of ParameterizedTypeReference, it uses reflection to capture information about the class type we want to convert our response to.
It holds on to this information using Java’s Type object, and we no longer have to worry about type erasure.