【实战问题】【15】报错java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast t...

场景重现:调用封装好的接口,返回的数据类型是List,debug能够看到有返回值。可是进行到对list进行操做的那步,报错了(java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xx)。原来list中的数据是LinkedTreeMap 格式的,并无转换成对应的实体类。网上查的方法不少是解决json格式字符串转成实体类,而我由于接收到的就是List数据,因此仍是想转成能使用的List数据。java

写在前面:尝试多种方法没有解决问题,最终是改了封装的接口,数据格式从源头就错了json

缘由:泛型<T>不能强转为List,会有一系列问题app

排查历程:post

(1)最开始个人代码ui

获取到了List,取出状态有效的数据。如此简单,开心。this

//主要代码
List<UserEntity> userList = this.commentService.getUserList(userId); //获取数据的接口
List<UserEntity> newList = list.stream().filter(i -> i.getStatus() == 1).collect(Collectors.toList()); //报错

而后就报错了,返回的数据格式是这样的:google

(2)在网上查这个报错,试了gson转list,没用url

Gson gson = new GsonBuilder().create(); //想着把list的值转成json格式的字符串
String userJson= gson.toJson(userList); //方式1
T[] array = gson.fromJson(userJson, UserEntity.class); List<UserEntity> newList = Arrays.asList(array); //方式2
List<UserEntity> list = (List<UserEntity>) gson.fromJson(userJson, new TypeToken<List<UserEntity>>() { }.getType());

(3)用ObjectMapper转,有用,可是数据格式匹配不上,报错。实体类中是Integer的值,在LinkedTreeMap中是Double了。spa

ObjectMapper mapper = new ObjectMapper(); List<UserEntity> list = mapper.convertValue(userList, new TypeReference<List<UserEntity>>() { }); 
//userList这里有点记不清了,不记得有没有用userJson。TODO

(4)用Map承接userList.get(0),再处理数据。可行,可是我还要作条件筛选,这个作不到个人需求debug

Map map = userList.get(0); UserEntity newInfo = new UserEntity (); newInfo.setName(map.get("name").toString()); ... //用for循环会报错。。。

(5)从源头解决问题

封装的接口里的List转换有问题

List<UserEntity> list = (List<UserEntity>) this.restClient.get(url, List.class); //这是调用了远程接口,restClient是封装了get,post通用方法,因此不能改,返回值原本是<T>

更改后:

JsonArray json= this.restClient.get(url, JsonArray.class); List<UserEntity> list = gson.fromJson(json, new TypeToken<List<UserEntity>>() {}.getType());
相关文章
相关标签/搜索