【问题标题】:Gson Nested classes are null while using proguard使用 proguard 时 Gson 嵌套类为空
【发布时间】:2019-07-19 16:40:22
【问题描述】:

警告:类“com.google.gson.internal.bind.ReflectiveTypeAdapterFactory”正在类上调用 Class.getDeclaredFields。

启用proguard后发现如下一些问题:

  1. 嵌套的静态类为空。
  2. 类中的自定义对象列表为空

已经参考了以下错误,但没有运气:

Proguard issue while using GSON Using GSON with proguard enabled

【问题讨论】:

    标签: java android gson proguard dexguard


    【解决方案1】:

    我可以通过对我的 proguard-rules.pro 文件执行三项操作来解决此问题:

    首先,确保ProGuard 不会更改您使用Gson 序列化的任何自定义类的名称。假设您有一个名为Classname 的类。要免除它,请将其添加到您的 progaurd-rules.pro

    -keepclassmembernames class com.your.package.classname { <fields>; }
    

    (将com.your.package.classname替换为您的实际包和类名)

    我不得不上十几堂课。不要忘记免除那些也是自定义的类的任何成员变量。使用 classname$innerclass 而不是 classname 来免除内部类。

    第二,添加Gson库推荐的规则。 They can be found here. 写这篇文章的时候是这样的:

    ##---------------Begin: proguard configuration for Gson  ----------
    # Gson uses generic type information stored in a class file when working with fields. Proguard
    # removes such information by default, so configure it to keep all of it.
    -keepattributes Signature
    
    # For using GSON @Expose annotation
    -keepattributes *Annotation*
    
    # Gson specific classes
    -dontwarn sun.misc.**
    #-keep class com.google.gson.stream.** { *; }
    
    # Application classes that will be serialized/deserialized over Gson
    -keep class com.google.gson.examples.android.model.** { <fields>; }
    
    # Prevent proguard from stripping interface information from TypeAdapter, TypeAdapterFactory,
    # JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
    -keep class * extends com.google.gson.TypeAdapter
    -keep class * implements com.google.gson.TypeAdapterFactory
    -keep class * implements com.google.gson.JsonSerializer
    -keep class * implements com.google.gson.JsonDeserializer
    
    # Prevent R8 from leaving Data object members always null
    -keepclassmembers,allowobfuscation class * {
      @com.google.gson.annotations.SerializedName <fields>;
    }
    
    # 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
    
    ##---------------End: proguard configuration for Gson  ----------
    

    最后,添加以下两条规则:

    -dontwarn java.lang.reflect.**
    -keep class kotlin.** { *; }
    

    这些解决了我遇到的嵌套 null 问题 - 当然,在我完成上述步骤之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2013-01-08
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多