在我的例子中,只是添加以下内容来混淆配置:
# Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken
这里是 Gson 所需的全套选项 -> https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg
嗯,更改我的
TypeToken
代码后,似乎它可以工作。
非工作代码:
return GsonBuilder().create().fromJson(
json,
object : TypeToken<List<Question>?>() {}.type
)
工作解决方案:
return GsonBuilder().create().fromJson(
json,
TypeToken.getParameterized(List::class.java, Question::class.java).type
)
在 proguard-rules.pro 中添加这 3 行:
-keep class com.google.gson.reflect.TypeToken
-keep class * extends com.google.gson.reflect.TypeToken
-keep public class * implements java.lang.reflect.Type
Android Gradle 插件 v8.0 进行了一些重大更改,包括启用 R8 完整模式: https://developer.android.com/build/releases/gradle-plugin#default-changes
如果其他选项(例如保留 TypeToken 类)都不适合您,您可以将以下命令添加到您的
gradle.properties
:
android.enableR8.fullMode = false
您可以在此处阅读有关 R8 完整模式的更多信息: https://r8.googlesource.com/r8/+/refs/heads/master/compatibility-faq.md#r8-full-mode
# Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken
-keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken
-keep class com.google.gson.reflect.TypeToken
-keep class * extends com.google.gson.reflect.TypeToken
-keep public class * implements java.lang.reflect.Type
就我而言,我必须保留模型类和 TypeToken,如果我删除任何一个,它就不起作用。
用于保留模型类
# Application classes that will be serialized/deserialized over Gson
-keep class com.example.data.models.** { *; }
用于保留TypeToken
# This is also needed for R8 in compat mode since multiple
# optimizations will remove the generic signature such as class
# merging and argument removal.
# 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