My code works perfectly without proguard, but GSON doesn\'t work when proguard is enabled.
This is the part of code where it doesn\'t works
JSONArray
Variable names will be obfuscated with proguard, leaving you with something like
private String a;
Instead of
private String descripcionCategoria;
You can add proguard rules so some classes don't get obfuscated. I got away with it using these:
-keepattributes Signature
# POJOs used with GSON
# The variable names are JSON key values and should not be obfuscated
-keepclassmembers class com.example.apps.android.Categorias { <fields>; }
# You can apply the rule to all the affected classes also
# -keepclassmembers class com.example.apps.android.model.** { <fields>; }
If your POJO class name is also used for parsing then you should also add the rule
-keep class com.example.apps.android.model.** { <fields>; }
In your case, annotations are not used, you would need this if you do
# Keep the annotations
-keepattributes *Annotation*
Another way to solve this problem is to use the SerializedName
annotation and let the class get obfuscated. For this you will still need the -keepattributes *Annotation*
rule.
import com.google.gson.annotations.SerializedName
@SerializedName("descripcionCategoria")
private String descripcionCategoria;
If you want your models still being obfuscated use annotation @SerializedName("name_of_json_field")
. It will let gson know the real name of the field.
I believe you will also need
-keepattributes *Annotation*
to keep your annotations from obfuscation
Changing this
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
to this worked for me
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
in your app's build.gradle file.
FYI, https://developer.android.com/studio/build/shrink-code
You need to exclude obfuscating of your model classes like below where I excluded all model classes in package in.intellicode.webservices.models
-keep class in.intellicode.webservices.models.** { *; }
-keep class in.intellicode.models.** { *; }
-keep class in.intellicode.events.*{ *; }
-keepattributes Signature
-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
When you apply proguard script to your model classes it obfuscates their names and their properties' names. So after obfuscation of String descripcionCategoria;
you will have something like String aaaa;
Gson works through java reflection and it will try to use a property name while parsing data. So, after applying obfuscation to model classes you won't be able to parse your data.
So, exclude model classes from your proguard script and you will be able to parse again.