700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Fegin RPC调用远程接口返回值解析问题:java.util.LinkedHashMap cannot be cast to com.xxx.xxx

Fegin RPC调用远程接口返回值解析问题:java.util.LinkedHashMap cannot be cast to com.xxx.xxx

时间:2023-03-20 04:37:58

相关推荐

Fegin RPC调用远程接口返回值解析问题:java.util.LinkedHashMap cannot be cast to com.xxx.xxx

现象:

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这个对象,问题解决。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。