LinkedHashMap cannot be cast to xxx解决方法

最近在做一个分布式项目,在远程调用的时候出现了一个问题,先上代码

服务提供者

 @GetMapping("/article/byType/{type}")
 @ResponseBody
 private List<Article> selectByType(@PathVariable("type") Integer type){
     return articleService.selectTextByType(type);
 }

我们这里是想要查询出来同属一个类型的文章,服务的详细代码不再赘述。我们再来看看服务消费者这边

 @GetMapping({"/","/index"})
 public String selectByType(Model model){
     List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PROVIDER");
     ServiceInstance instance = instances.get(0);
     URI uri = instance.getUri();
     String url = uri+"/article/byType/"+2;
     List<Article> articleList = restTemplate.getForObject(url, List.class);
     for (Article article : articleList) {
         System.out.println(article.getArticleTitle());
     }
     //...
 }

在测试的时候,我本来是想先输出看一下结果的,也就是上面的代码,结果却发现出错了
在这里插入图片描述
类型转换异常,说是LinkedHashMap无法转换成Article,这是为什么?

我们来看一看我们遍历的到底是个什么玩意儿

在这里插入图片描述
原来给我们返回的是一个LinkedHashMap的List集合,所以才会出现这个类型转换错误。我们接下来看看解决办法

1、我们需要先导入一个fastjson的包。

2、我们需要先将返回过来的值变成一个Json字符出串。

3、然后我们可以使用fastjson中的工具类将这个Json字符串转换成一个List集合。

    public String selectByType(Model model){
        List<ServiceInstance> instances = discoveryClient.getInstances("SERVICE-PROVIDER");
        ServiceInstance instance = instances.get(0);
        URI uri = instance.getUri();
        String url = uri+"/article/byType/"+2;
        List articleMap = restTemplate.getForObject(url, List.class);
        // 我们需要先将返回过来的值变成一个Json字符出串。
        String s = JSON.toJSONString(articleMap);
        // 将这个Json字符串转换成一个List集合。
        List<Article> articleList = JSONObject.parseArray(s, Article.class);
        ArrayList<Article> articles = new ArrayList<>();
        for (Article art : articleList) {
            articles.add(art);
        }
    }

在这里插入图片描述

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值