以下代码通常对我有用:
val users: Array<Catalog> = com.google.gson.Gson().fromJson(data, Array<MyUserClass>::class.java)
但是,当我启用ProGuard时,出现以下错误:


MyUserClass如下:
data class MyUserClass(var posts: List<UserPosts>)
因此,Gson正确地将users设置为MyUserClass-但不是MyUserClassUserPosts的列表,而是最终成为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

08-18 17:51