ProGuard让Gson返回LinkedTreeMap而不是我的类型

时间:2017-07-14 14:24:26

标签: java android gson kotlin proguard

以下代码行通常适用于我:

val users: Array<Catalog> = com.google.gson.Gson().fromJson(data, Array<MyUserClass>::class.java)

但是当我启用ProGuard时,我收到此错误:

  

java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap   无法转换为com.example.app.Models.MyModel

MyUserClass如下:

data class MyUserClass(var posts: List<UserPosts>)

所以Gson正确地使users成为MyUserClass - 但MyUserClass不是UserPosts,而是LinkedTreeMap的列表< / p>

我一直试图解决这个问题一段时间了,我发现与此相关的所有答案都与泛型有关,但我没有使用泛型,我将这个类直接传递给Gson。 / p>

此时我完全迷失了,所以任何指导都会受到赞赏

以下是相关的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

1 个答案:

答案 0 :(得分:2)

确保您的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