首页 > 解决方案 > 通用扩展的 Android proguard 规则

问题描述

我创建了一个 gson 扩展来序列化和反序列化对象,如下所示。

/**
 * To serialize the object to json string
 */

    fun Any.toGson(): String {
        return Gson().toJson(this)
    }

/**
 * To deserialize the json string to object of type <T>
 */

    fun <T>String.toObject() : T{
        return Gson().fromJson(this, object : TypeToken<T>() {}.type)
    } 

当我在发布模式下构建项目时,应用程序由于 proguard 规则而崩溃。

我添加了 proguard 规则 -keepattribute 签名。应用程序仍然崩溃。

2020-11-24 08:47:28.448 8215-8215/? E/Paramthrowable Stacktrace 错误:Throwable java.lang.AssertionError:libcore.reflect.TypeVariableImpl.getGenericDeclaration(TypeVariableImpl.java:125) 处的 libcore.reflect.TypeVariableImpl.resolve(TypeVariableImpl.java:111) 处的非法类型变量引用。 reflect.TypeVariableImpl.hashCode(TypeVariableImpl.java:47) 在 bcava(TypeToken.java:9) 在 baaaea(ListExtension.kt:1) 在 ouuf(ViewGroupUtilsApi14.java:11)

以上是堆栈跟踪。ListExtension 包含问题需要帮助解决此问题中提到的代码。

标签: androidkotlingsonproguardkotlin-extension

解决方案


##---------------Begin: proguard configuration for Gson  ----------

-keepattributes Signature

# Gson specific classes
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }

# Application classes that will be serialized/deserialized over Gson
# -keep class mypersonalclass.data.model.** { *; }

添加保留模型的规则,我认为您的扩展功能在模型类中


推荐阅读