下面这行代码对我来说很正常:
val users: Array<Catalog> = com.google.gson.Gson().fromJson(data, Array<MyUserClass>::class.java)
但是当我启用 ProGuard 时,我得到这个错误:
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.example.app.Models.MyModel
MyUserClass
如下:
data class MyUserClass(var posts: List<UserPosts>)
所以 Gson 正确地使 users
是MyUserClass
- 但不是 MyUserClass
是 UserPosts
的列表, 它最终成为 LinkedTreeMap
的列表
我已经尝试解决这个问题一段时间了,我找到的所有与此相关的答案都与泛型有关,但我没有使用泛型,而是将类直接传递给 Gson。
我现在完全迷路了,所以任何指导都将不胜感激
这是相关的 ProGuard 规则:
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
-keep class com.example.Models.** { *; }
# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
##---------------End: proguard configuration for Gson ----------
-keep public class MyUserClass
-keep public class UserPosts
最佳答案
确保您的 proguard.cfg 包含所有规则:
##---------------Begin: proguard configuration for Gson ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature
# For using GSON @Expose annotation
-keepattributes *Annotation*
# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson
-keep class com.google.gson.examples.android.model.** { *; }
# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements com.google.gson.TypeAdapterFactory
-keep class * implements com.google.gson.JsonSerializer
-keep class * implements com.google.gson.JsonDeserializer
##---------------End: proguard configuration for Gson ----------
-keep public class MyUserClass
-keep public class UserPosts
关于java - ProGuard 让 Gson 返回 LinkedTreeMap 而不是我的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45105334/