Gson混淆配置的一些小坑

Gson就不介绍了,援引一下官方的哈哈:

A Java serialization/deserialization library to convert Java Objects into JSON and back

我们在配置Proguard配置文件时,都会用Gson官方文档给出的:

##---------------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
# 注意这里只是谷歌的一个示例,具体需要替换成你自己的各种data、entity、bean等类
-keep class com.google.gson.examples.android.model.** { <fields>; }

# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-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>;
}

##---------------End: proguard configuration for Gson  ----------

源码地址在:https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg
如果你的数据类都是继承形式的,大部分情况下不会有什么问题。
但如果项目中有接口形式标记的类拿到Gson中解析,就会有问题:

public class MyData implements BaseData {
    private String name;
    ...
}

可能出现类对象能反序列化,但解析出来成员变量都是空的。
这种情况下就要加一下配置了,最好先keep住接口类:

@Keep
public interface BaseData {
}

然后在混淆配置文件中加:

-keep class * implements com.xxx.xxx.BaseData {*;}

就OK了。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页