I'm trying to return a ResponseEntity
list and casting that response respect to my model classes.
For instance: if I use ResponseEntity<List<ApplicationModel>>
it's working well but I do not want to write a response method per model.
ResponseEntity
method
public static <T> ResponseEntity<List<T>> getResponseList(String resourceURL) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<List<T>> entity = new HttpEntity<List<T>>(headers);
ResponseEntity<List<T>> response = restTemplate.exchange(resourceURL, HttpMethod.GET, entity,
new ParameterizedTypeReference<List<T>>() {
}, Collections.emptyMap());
return response;
}
Method call
private final String url ="http://localhost:8090/xxx/application";
ResponseEntity<List<ApplicationModel> responseForApplications =
ResponseTemplate.getResponseList(url);
if (responseForApplications.getStatusCode() == HttpStatus.OK)
List<ApplicationModel> dtoApplications = responseForApplications.getBody();
Example of JSON response which I want to cast
{"id":1,"name":"foo","description":"foo"}
Error
There was an unexpected error (type=Internal Server Error, status=500). Error creating bean with name 'index': Invocation of init method failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.xxx.ApplicationModel