Google Gson 保留泛型签名

huangapple go评论56阅读模式
英文:

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.

英文:

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.

答案1

得分: 4

以下是翻译好的内容:

需要对Gson进行序列化/反序列化类的排除。对于包含您的类的包,看起来像这样

# 将在Gson上序列化/反序列化的应用程序类
-keep class com.myapplication.model.api.** { *; }

还需添加以下内容

# Gson在处理字段时使用存储在类文件中的通用类型信息。
# Proguard默认情况下会删除这样的信息,要保留它。
-keepattributes Signature

# 这也是R8兼容模式下所需的,因为多个优化将删除通用签名,如类合并和参数删除。
-keep class com.google.gson.reflect.TypeToken { *; }
-keep class * extends com.google.gson.reflect.TypeToken

# 可选的。用于使用GSON @Expose注解
-keepattributes AnnotationDefault,RuntimeVisibleAnnotations
英文:

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

huangapple
  • 本文由 发表于 2023年5月11日 15:07:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224936.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定