【實戰問題】【15】報錯java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xx


場景重現:調用封裝好的接口,返回的數據類型是List,debug可以看到有返回值。但是進行到對list進行操作的那步,報錯了(java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xx)。原來list中的數據是LinkedTreeMap 格式的,並沒有轉換成對應的實體類。網上查的方法很多是解決json格式字符串轉成實體類,而我因為接收到的就是List數據,所以還是想轉成能使用的List數據。

寫在前面:嘗試多種方法沒有解決問題,最終是改了封裝的接口,數據格式從源頭就錯了

原因:泛型<T>不能強轉為List,會有一系列問題

排查歷程:

(1)最開始我的代碼

獲取到了List,取出狀態有效的數據。如此簡單,開心。

//主要代碼
List<UserEntity> userList = this.commentService.getUserList(userId); //獲取數據的接口
List<UserEntity> newList = list.stream().filter(i -> i.getStatus() == 1).collect(Collectors.toList()); //報錯

然后就報錯了,返回的數據格式是這樣的:

(2)在網上查這個報錯,試了gson轉list,沒用

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了。

ObjectMapper mapper = new ObjectMapper();
List<UserEntity> list = mapper.convertValue(userList, new TypeReference<List<UserEntity>>() { }); 
//userList這里有點記不清了,不記得有沒有用userJson。TODO

(4)用Map承接userList.get(0),再處理數據。可行,但是我還要做條件篩選,這個做不到我的需求

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());

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM