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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值