Gson do not deserialize fields that never used

370 views Asked by At

Current situation
I have a model, where class UserSettingModel have two field : long UserId and have as field one exemplar of class UserSettings ( with many field ) with name Settings.

WARNING : none of this fields used directly in my code ( in Android Studio color of this fields is gray), but I need to resend it to server.

public class UserSettingsModel
{
    @SerializedName("UserId")
    public long UserId = -1L;

    @SerializedName("Settings")
    public UserSettings Settings;

}//end of class/ UserSettingsModel

class UserSettings
{
    @SerializedName("showRegion")
    public String showRegion = "";

    @SerializedName("showAddress")
    public String showAddress = "";
}

Problem
If working with apk in DEBUG mode : GSON deserialize all field of class UserSettingModel, including Settings

If working with apk in RELEASE mode : field Settings - not deserialize

My proguard :

-keepattributes Signature
-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
-keep class com.google.gson.examples.android.model.** { *; }
-keep class com.google.gson.** { *; }
-keepclassmembers enum * { *; }
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer

What I need
How to serialize/deserialize with GSON in Release mode ALL FIELD of classes, also with warning "field is never used" ?

1

There are 1 answers

0
Aorlinn On

This is because of obfuscation, as DQuade states in the comment.

To prevent gradle from removing them, you can either add the specific class in your proguard-rules.pro file:

-keepclassmembers class [yourPackageName].UserSettingsModel
-keepclassmembers class [yourPackageName].UserSettings

or prevent gradle from removing all members annotated with the SerializedName annotation:

-keepclassmembers class * {
  @com.google.gson.annotations.SerializedName <fields>;
}