Android Gson 混淆問題


開發過程中遇到一個奇怪的問題。
有一個接口,debug 版本接收到雲側下發的字符串后可以通過 gson 將其轉換為相應 bean 類,而 release 版本拿到的 bean 總是缺少一個關鍵的字段,使得正常的邏輯根本走不通,很是不解。
在同事的提醒下,我打印了下端側使用 gson 轉化后的 bean 的類型,這才發現這時的類型已經變成了一些凌亂的英文字符,很顯然這時拿到的 bean 已經是經過混淆了的,這些 bean 類不應該被混淆。
從網上找了下 Gson 官方提供的混淆樣板,鏈接在https://github.com/google/gson/blob/master/examples/android-proguard-example/proguard.cfg,可以看到其樣板代碼如下:

##---------------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
# 此處需修改成自己項目中的 bean 類位置
-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  ----------

修改上面一行為項目中 bean 類的位置,問題就解決了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM