You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gson反序列化引发ClassCastException:LinkedTreeMap无法转为Profile

解决Gson反序列化ClassCastException(LinkedTreeMap转Profile)问题

异常信息

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.xxx.Profile

调用栈:

Caused by: java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.xxx.Profile
  at com..CDManagmentHelper.getProfileLisWOHomeUnmanaged(SourceFile:1901)

问题根源

生产环境开启ProGuard混淆后,泛型类型信息被擦除,Gson无法识别RouterStatusModel中List<Profile>的具体泛型类型,导致反序列化时将列表元素默认转为LinkedTreeMap而非Profile实例,循环强转时抛出类型转换异常。现有ProGuard规则未保留自定义实体类的泛型签名及完整结构,是核心原因。

解决方案

1. 补充ProGuard规则,保留实体类与泛型信息

在现有Gson规则中添加以下配置:

# 保留自定义实体类的完整结构,避免混淆
-keep class com.xxx.Profile { *; }
-keep class com.xxx.RouterStatusModel { *; }

# 保留泛型签名,让Gson能识别List<Profile>的具体类型
-keepattributes Signature
  • -keepattributes Signature是关键:它会保留类和方法的泛型签名,Gson依赖此信息完成正确的泛型反序列化。
  • 替换com.xxx为实际的包名,确保覆盖你的实体类。

2. 清理冗余ProGuard规则

现有规则中重复保留了TypeToken,可合并为以下精简版本:

# Retain generic signatures of TypeToken and its subclasses
-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken

3. 确保反序列化时的类型正确性(可选加固)

如果反序列化RouterStatusModel的代码未明确指定泛型类型,可改为以下写法,进一步避免类型丢失:

// 使用TypeToken明确指定泛型类型
Type routerStatusType = new TypeToken<RouterStatusModel>() {}.getType();
RouterStatusModel routerStatusModel = gson.fromJson(jsonResponse, routerStatusType);

验证步骤

  1. 应用更新后的ProGuard规则,重新构建生产包。
  2. 测试接口反序列化流程,确认getProfileLisWOHomeUnmanaged方法中的循环不再抛出类型转换异常。
  3. 检查混淆后的映射文件(mapping.txt),确认Profile和RouterStatusModel的类名、字段名未被混淆。

内容的提问来源于stack exchange,提问作者Varsha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:40:58