ClassCastException: RestTemplate returning List<LinkedHashMap> instead of List<MymodelClass>

拟墨画扇 提交于 2019-11-28 05:20:16

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!