Google Gson 保留通用签名

S. *_*sel 10 generics proguard gson android-r8

Firebase Crashlytics 中出现崩溃,并附有如何解决问题的注释:

致命异常:java.lang.IllegalStateException:必须使用类型参数创建 TypeToken:new TypeToken<...>() {}; 使用代码压缩器(ProGuard、R8...)时,请确保保留通用签名。

我的尖括号 <...> 之间的通用类名为ApiResponse我用jsonschema2pojo创建它。

S. *_*sel 23

需要排除 Gson 上的序列化/反序列化类。对于包含您的类的包,如下所示

# Application classes that will be serialized/deserialized over Gson
-keep class com.myapplication.model.api.** { *; }
Run Code Online (Sandbox Code Playgroud)

还要添加这个

# Gson uses generic type information stored in a class file when working with
# fields. Proguard removes such information by default, keep it.
-keepattributes Signature

# This is also needed for R8 in compat mode since multiple 
# optimizations will remove the generic signature such as class 
# merging and argument removal. See: 
# https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#troubleshooting-gson-gson
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken

# Optional. For using GSON @Expose annotation
-keepattributes AnnotationDefault,RuntimeVisibleAnnotations
Run Code Online (Sandbox Code Playgroud)

  • 您确定这解决了问题吗?另请查看 https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#troubleshooting-gson-gson,其中解释了“TypeToken”处理。 (5认同)
  • 完整的混淆器文件:https://github.com/google/gson/blob/main/gson/src/main/resources/META-INF/proguard/gson.pro (2认同)