Search code examples
javaandroidserializationproguard

Android, using proguard and serialization


We noticed that in our proguard-rules.pro we were missing the

-keep class com.thecompany.theapp.datamodel.** { *; } 

line, that kept our serializable data objects. And this caused the app to crash when parsing serialized User objects which we had changed by removing unused setters/getters (did not remove the fields). As we understand this is okay according to http://docs.oracle.com/javase/7/docs/platform/serialization/spec/version.html#6678

After we added the -keep line to proguard-rules.pro and debugged the serializedUser string with the fields still obfuscated (a, b, c etc) the Gson parser still managed to parse the serialized string (yay!). But why?! Wouldn't the Gson parser expect the fields to be non-obfuscated?

Will this mean problems later, when we go from obfuscated to non-obfuscated data? Can anyone provide some clarity regarding how the interaction between proguard and Gson parsing serialized objects work?

This is how we are parsing the data objects using Gson:

String serializedUser = EncPrefUtil.decryptStringPref(context, R.string.pref_key_user);
User user = !TextUtils.isEmpty(serializedUser) ? new Gson().fromJson(serializedUser, User.class) : new User();

Solution

  • The Gson parser would expect the fields to be non-obfuscated but that would not make it crash. It would parse the object and find none of the corresponding fields and then initialize the fields to their default values.

    It could crash if there was a match between an obfuscated field name and an original field name (for fields of different types). Could happen for example if you got variables named 'x' and 'y' or such, as that is a name the obfuscation could come up with.

    So you can't simply swap from obfuscated to non obfuscated, you could implement your own parser and have a transition step which translates the old 'bad' obfuscated serialization to the new unobfuscated object and then serialize that.

    This may be helpful How do I write a custom JSON deserializer for Gson?