ClassCastException: RestTemplate returning List instead of List

With the following method call

List<MyModelClass> myModelClass=(List<MyModelClass>) restTemplate.postForObject(url,mvm,List.class);

All Jackson knows is that you want a List, but doesn’t have any restriction on the type. By default Jackson deserializes a JSON object into a LinkedHashMap, so that’s why you are getting the ClassCastException.

If your returned JSON is an array, one way to get it is to use an array

MyModelClass[] myModelClasses = restTemplate.postForObject(url,mvm, MyModelClass[].class);

You can always add the elements from that array to a List.

I can’t remember since what version, but RestTemplate#exchange now has an overload that accepts a ParameterizedTypeReference argument. The ParameterizedTypeReference is the type token hack for suggesting a parameterized type as the target for deserialization.

You can refactor the code above to use exchange instead of postForObject, and use ParameterizedTypeReference to get a List<MyModelClass>. For example

ParameterizedTypeReference<List<MyModelClass>> typeRef = new ParameterizedTypeReference<List<MyModelClass>>() {
};
ResponseEntity<List<MyModelClass>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(mvm), typeRef);
List<MyModelClass> myModelClasses = responseEntity.getBody();

Leave a Comment