【问题标题】:Caused by java.lang.RuntimeException: Missing type parameter由 java.lang.RuntimeException 引起:缺少类型参数
【发布时间】:2022-03-03 00:52:39
【问题描述】:

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

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

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

可能Question 类型被混淆或发生类似情况。 我的 proguard 文件:

-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

也许我必须在 proguard 文件中添加一些内容?

附注问题仅出现在 Gradle 7.1.0

【问题讨论】:

  • 可能是stackoverflow.com/q/8129040的副本;但是这有点奇怪,这只是从 Gradle 7.1.0 开始出现
  • 这是关于 Gradle 7.1 还是 Android Gradle 插件 7.1.0?
  • 这是应用程序gradle文件中的com.android.tools.build:gradle版本。
  • Gson issue #2069 也描述了这个问题,但目前还没有已知的解决方案(除了下面提到的解决方法)。
  • 谢谢。顺便说一句,我会保留这个问题,因此有人会觉得这很有用。

标签: android kotlin gson proguard typetoken


【解决方案1】:

在我的情况下,只是将以下内容添加到 proguard 配置中:

# 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

【讨论】:

  • 谢谢.. 如果 minifyEnabled 为真,这将有所帮助
【解决方案2】:

好吧,在更改了我的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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2011-12-29
    • 2017-10-30
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多