GSON:仅在已发布的应用程序中使用我的 JSONEntity 无法正确创建,使用 Android Studio 可以正常工作

GSON: Not creating correctly using my JSONEntity only in published app, using Android Studio it works fine

我的问题只发生在已发布的 apk 上。通过 Android Studio 安装的应用程序可以正常运行。但是通过 Google 安装的 Play 正在错误地使用 GSON 库生成我的 JSON 文件,似乎它没有在已发布的 apk 上使用我的 JSONEntity。

正确:使用 Android Studio 在我的应用程序上生成的文件:

{
  "categories": [
    {
      "_id": 1,
      "name": "General"
    },
....

错误:通过从 Google Play 下载应用程序生成:

{
  "a": [
    {
      "a": 1,
      "b": "General"
    }
  ],
...

知道为什么这只发生在 Google Play 上发布的应用程序上吗?

这个问题是由混淆器引起的。 ProGuard 更改了 Android 代码(出于安全考虑)但为了避免解析错误,需要在使用的 JSON 文件上添加 "exceptions"。

默认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.** { *; }

##---------------End: proguard configuration for Gson  ----------

并且特定于我使用过的 classes 的字段名称,还添加了:

-keepclassmembers class com.xxxxx.xxx.JSONEntity$XxxxEntity { <fields>; }
-keepclassmembers class com.xxxxx.xxx.JSONEntity { <fields>; }

对于我要生成的每个 class 文件,每个属性的特定字段名称使用上面的代码替换 class 名称。