由 java.lang.RuntimeException 引起:缺少类型参数

Hay*_*yan 13 android proguard gson kotlin typetoken

我正在检索 a json,当我使用 将其转换为列表时gson,应用程序崩溃了。已proguard打开,问题就在那里。

fun getQuestions(): List<Question>? {
    val json = getQuestionsJsonData()
    return GsonBuilder().create().fromJson(
        json,
        object : TypeToken<List<Question>?>() {}.type
    )
}
Run Code Online (Sandbox Code Playgroud)

由于我混淆了我的代码,我无法看到crashlog in logcat,所以我将其发送到firebase crashlitycs. 错误消息是 -Caused by java.lang.RuntimeException: Missing type parameter.

也许Question类型被混淆了或者发生了类似的事情。我的混淆器文件:

-keepclassmembers,allowobfuscation class * {
  @com.google.gson.annotations.SerializedName <fields>;
}

-keepclassmembers class **.R$* {
    public static <fields>;
}

#Serialized
-keepnames class * implements java.io.Serializable
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    !static !transient <fields>;
    !private <fields>;
    !private <methods>;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

# Uncomment this to preserve the line number information for
# debugging stack traces.
-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
-renamesourcefileattribute SourceFile
Run Code Online (Sandbox Code Playgroud)

也许我必须在 proguard 文件中添加一些东西?

PS 该问题仅出现在 Gradle 7.1.0 上

for*_*ayo 38

就我而言,只是将以下内容添加到混淆器配置中:

# 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
Run Code Online (Sandbox Code Playgroud)

这里是 Gson 所需的全套选项 -> https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg


Hay*_*yan 17

好吧,更改我的TypeToken代码后,似乎它可以工作。

非工作代码:

return GsonBuilder().create().fromJson(
    json,
    object : TypeToken<List<Question>?>() {}.type
)
Run Code Online (Sandbox Code Playgroud)

工作解决方案:

return GsonBuilder().create().fromJson(
    json,
    TypeToken.getParameterized(List::class.java, Question::class.java).type
)
Run Code Online (Sandbox Code Playgroud)