开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情
问题描述
今天在使用RestTemplate调用服务的时候,因为服务提供者返回的是一个List集合,所以在使用消费者调用的时候,restTemplate.getForObject()期待返回的类型直接写成了List.class
相关代码如下
String url = serviceUrl + "/common/getFilePath";
List<DocInfoRela> docInfoRelas = restTemplate.getForObject(url, List.class);
return docInfoRelas;
}
生产者代码
消费者代码
但是接收到List之后,在便利的时候却报错了,报错内容如下:
java.lang.ClassCastException: java.util.[LinkedHashMap](https://so.csdn.net/so/search?q=LinkedHashMap&spm=1001.2101.3001.7020) cannot be cast to cn.chinatowercom.postaccounting.entity.DocInfoRela
ERROR 2022-11-17 15:09:32 [dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to cn.chinatowercom.postaccounting.entity.DocInfoRela] with root cause
相关代码和如图截图:
解决问题
我个人比较喜欢这种方案
定义返回List
String url = serviceUrl + "/common/getFilePath";
List<DocInfoRela> docInfoRelas = restTemplate.getForObject(url, List.class);
return docInfoRelas;
}
然后将list再次转为json串,然后由json串再转为list
代码如下:
List<DocInfoRela> DocInfoRelasList = this.getFilePath();
// 将list再次转为json串,然后由json串再转为list
String docInfoRelaStrings = JSON.toJSONString(DocInfoRelasList);
DocInfoRelasList = JSON.parseArray(docInfoRelaStrings, DocInfoRela.class);