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

Jon*_*ira 2 android gson

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

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

{
  "categories": [
    {
      "_id": 1,
      "name": "General"
    },
....
Run Code Online (Sandbox Code Playgroud)

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

{
  "a": [
    {
      "a": 1,
      "b": "General"
    }
  ],
...
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*ira 6

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

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  ----------
Run Code Online (Sandbox Code Playgroud)

针对我所使用的类的字段名称,还添加了:

-keepclassmembers class com.xxxxx.xxx.JSONEntity$XxxxEntity { <fields>; }
-keepclassmembers class com.xxxxx.xxx.JSONEntity { <fields>; }
Run Code Online (Sandbox Code Playgroud)

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