使用proguard时,Gson嵌套类为空

8xiog9wr  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(228)

警告:类别'com.google.gson.internal.bind.ReflectiveTypeAdapterFactory'正在呼叫类别上的类别.getDeclaredFields。
启用proguard后,发现以下问题:
1.嵌套的静态类为空。
1.类中的自定义对象列表为空
已经引用了下面的bug,但是没有运气:
Proguard issue while using GSONUsing GSON with proguard enabled显示器

0x6upsns

0x6upsns1#

我通过对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问题的解决方法--当然,是在我完成上述步骤之后。

相关问题