正式版本Gson不工作

1,098 阅读1分钟

公司项目需要解析Json数据,为了方便,所以引入了Gson库。在Debug模式下面可以正常运行,但是发布release版本给测试人员测试,项目可以正常运行,但是数据貌似没有解析出来,而且log显示App已经正常显示收取到Json数据,但是在Gson解析数据的地方停止了。

val mapData = Gson().fromJson(message, PushMessage::class.java)

class PushMessage {
    var display_type: String? = null
    var msg_id: String? = null
    var body: Custom? = null

    inner class Custom {
        var custom: Map<String, String>? = null
    }
}

通过检查了Gson官方Demo,发现了引入Gson库的时候,如果工程中使用了配置了混淆文件,需要添加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
-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>;
}

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

需要注意的是这句代码:

-keep class com.google.gson.examples.android.model.** { <fields>; }

需要修改成为你自己需要解析成为的类,而且如何类中含有内部类,需要单独配置内部类,以PushMessage为例:

-keep class YourPakeagename.PushMessage { *; }
-keep class YourPakeagename.PushMessage$Custom { *; }

然后就可以正常运行并使用Gson了。