Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Gson preserve generic signatures

Crashes in Firebase Crashlytics appear with a note how to fix a problem:

Fatal Exception: java.lang.IllegalStateException: TypeToken must be created with a type argument: new TypeToken<...>() {}; When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.

My generic class between angle brackets <...> is named ApiResponse. I created it with jsonschema2pojo.

like image 653
S. Gissel Avatar asked Sep 12 '25 21:09

S. Gissel


2 Answers

An exclusion for serialized/deserialized classes over Gson is needed. For a package containing your classes looks like this

# Application classes that will be serialized/deserialized over Gson
-keep class com.myapplication.model.api.** { *; }

Also add this

# Gson uses generic type information stored in a class file when working with
# fields. Proguard removes such information by default, keep it.
-keepattributes Signature

# This is also needed for R8 in compat mode since multiple 
# optimizations will remove the generic signature such as class 
# merging and argument removal. See: 
# https://r8.googlesource.com/r8/+/refs/heads/main/compatibility-faq.md#troubleshooting-gson-gson
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken

# Optional. For using GSON @Expose annotation
-keepattributes AnnotationDefault,RuntimeVisibleAnnotations
-keep class com.google.gson.reflect.TypeToken { <fields>; } 
-keepclassmembers class **$TypeAdapterFactory { <fields>; }
like image 51
S. Gissel Avatar answered Sep 14 '25 12:09

S. Gissel


All of these proguard rules has been added automatically on Gson 2.11.0

so just upgrade the Gson dependency

like image 43
Andrea Liureta Avatar answered Sep 14 '25 14:09

Andrea Liureta