最近在做一个分布式项目,在远程调用的时候出现了一个问题,先上代码
服务提供者
@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); } }