现象:
BaseResponse 对象中有个Property名为result,为Object 类型,接口为这个result赋值是一个Map<String, NodeDetail> 对象,结果在用Map<String, NodeDetail> 类型强转result时报错:java.util.LinkedHashMap cannot be cast to com.xxx.xxx.NodeDetail。
Map<String, NodeDetail> result = (Map<String, NodeDetail>) result;
所报异常:
java.util.LinkedHashMap cannot be cast to com.xxx.xxx.NodeDetail
原因:
Map中的NodeDetail对象被转成了LinkedHashMap,所以无法直接用NodeDetail接收
接口:
feign接口与远程服务的Controller接口相同,接口如下:
@ApiOperation(value = "查询对象详情", produces = "application/json")
@PostMapping(value = "/opcua/queryDetailByRootUri")
BaseResponse queryDetailByRootUri(@RequestParam("uri") String uri,
@RequestParam(required = false, value = "extendParentProperties") boolean extendParentProperties,
@RequestParam(required = false, value = "boolean") boolean containSubtype);
解决方法:
使用 org.codehaus.jackson.map.ObjectMapper 转换对象。
Map<String, Map> result = (Map<String, Map>) baseResponse.getResult();
Map<String, NodeDetail> newResult = new HashMap<>();
Set<String> keys = result.keySet();
for(String key : keys){
ObjectMapper mapper = new ObjectMapper();
NodeDetail nd = mapper.convertValue(keys .get(key), NodeDetail.class);
newResult .put(key, nd);
}
原result转为newResult对象,在后面使用newResult这个对象,问题解决。