问题描述:
最近有个接口,明明接受对象是同一个,但是却报错
代码如下
系统A 的接口
java
@RestController
@RequestMapping("log")
public class LogController {
@GetMapping("getLog")
List<LogInfo> getLog(){
List<LogInfo> logInfos = new ArrayList<>();
LogInfo logInfo = new LogInfo();
logInfo.setMsg("1");
logInfo.setName("t1");
LogInfo logInfo2 = new LogInfo();
logInfo2.setMsg("2");
logInfo2.setName("t2");
logInfos.add(logInfo);
logInfos.add(logInfo2);
return logInfos;
}
}
系统B接入
java
@RestController
@RequestMapping("myService")
public class MyController {
@Resource
RestTemplate restTemplate;
@GetMapping("getLog")
Result<List<LogInfo>> getLog(){
List<LogInfo> logInfos = restTemplate.getForObject("http://localhost:9001/log/getLog", List.class);
return Result.OK(logInfos);
}
@GetMapping("deal")
Result<?> deal(String name){
Result<List<LogInfo>> log = getLog();
List<LogInfo> logInfos = log.getData();
Map<String, List<LogInfo>> collect = logInfos.stream().collect(Collectors.groupingBy(LogInfo::getName));
return Result.OK(collect.get(name));
}
}
猜猜哪个方法报错了
接收没问题,处理报错了

这个错误是因为在使用RestTemplate时,没有指定返回的List中的元素类型,导致RestTemplate将JSON反序列化为List,而不是List。
当我们尝试将LinkedHashMap转换为LogInfo时,就会抛出ClassCastException。
解决方法
方案一:使用exchange方法,并传递ParameterizedTypeReference
java
@GetMapping("exchange")
Result<?> exchange(String name){
ResponseEntity<List<LogInfo>> responseEntity = restTemplate.exchange(
"http://localhost:9001/log/getLog",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<LogInfo>>() {});
List<LogInfo> logInfos = responseEntity.getBody();
Map<String, List<LogInfo>> collect = logInfos.stream().collect(Collectors.groupingBy(LogInfo::getName));
return Result.OK(collect.get(name));
}