What Happened?
So, AGP 8.0 and highers brings in R8 in “Full mode” as the default tool for code shrinking and obfuscation when minifyEnabled is set to true.
If you’re familiar with the transition from ProGuard to R8, this might feel a bit like déjà vu. But what really caught me off guard was how it impacted Gson.
If you were previously using ProGuard (or even R8 in “partial” mode) and relied on Gson for serialization, you probably didn’t have to worry too much about your code getting mangled. However, with R8 fully enabled, it starts aggressively removing unused code and obfuscating your method names, which—surprise!—can break your Gson code.
Why Does This Break Things?
Gson uses reflection to map Java objects to JSON and vice versa. Reflection depends on method and class names remaining intact, so R8’s aggressive optimizations might mistakenly remove or rename methods that Gson needs.
This leads to errors like:
- Missing classes or methods during runtime
- Gson unable to deserialize JSON properly
- Your app crashing unexpectedly (yikes!)
The Fix: Adding Proguard Rules
To make sure everything runs smoothly, you’ll need to explicitly tell R8 to keep certain classes, methods, and fields from being obfuscated or removed. This is where your trusty proguard-rules.pro
file comes in!
Here’s what I added to my proguard-rules.pro
file to make sure Gson plays nice with R8:
# Gson ProGuard Rules
# Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.
-keep,allowobfuscation class com.google.gson.reflect.TypeToken
-keep,allowobfuscation class * extends com.google.gson.reflect.TypeToken
Have you run into any similar issues with R8 or AGP updates? I wish this blog could help you more or less.