ClassCastException: RestTemplate returning List instead of List

Problem:

I have a POJO entity, say org.grassfield.Employee. I expose this as a REST services.

I consume this REST service,

[code language=”java”]

List employeeList = restTemplate.getForObject(
“http://localhost:8080/api/v1/employees” ,
List.class);

[/code]

Instead of getting Employee object, I’m getting LinkedHashMap. So my code fails with ClassCastException: RestTemplate returning List<LinkedHashMap> instead of List<Employee>

Solution:

Jackson uses LinkedHashMap to Serialize/De serialize the entity objects. When I consume the service using parameterized type reference, it works fine.

[code language=”java”]

ResponseEntity<List> response = restTemplate.exchange(
“http://localhost:8080/api/v1/employees” ,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List>(){});
List EmployeeList = response.getBody();

[/code]

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top