设置 minifyEnabled 为 true 时无法使用 GSON 解析 json 对象

Max*_*axB 5 android proguard gson kotlin

当我使用

buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
Run Code Online (Sandbox Code Playgroud)

一切都很完美。

但如果改为

buildTypes {
        release {
            minifyEnabled true
            useProguard true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
Run Code Online (Sandbox Code Playgroud)

我收到解析错误。

我的解析类:

data class SearchItem(
    @SerializedName("position") val position: Long,
    @SerializedName("user") val user: String?
) {
    fun getId(): Long {
        return 0L
    }
}

data class SearchResponse(
    @SerializedName("list") val list: List<SearchItem>,
    @SerializedName("has_more") val has_more: Boolean,
    @SerializedName("rank_token") val rank_token: String,
    @SerializedName("status") val status: String
)
Run Code Online (Sandbox Code Playgroud)

这里我使用gson:

val searchResponse = Gson().fromJson(jsonObject.toString(), SearchResponse::class.java)
Run Code Online (Sandbox Code Playgroud)

proguard-rules.pro我有一条非评论行-keepattributes *Annotation*

我将不胜感激任何帮助!

编辑 错误日志:

E/AndroidRuntime: FATAL EXCEPTION: k.c0 Dispatcher
    Process: PID: 31392
    java.lang.NullPointerException: throw with null exception
        at h.a.a.j.a.a.a(:2)
        at k.l0.g.e$a.run(:6)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
        at java.lang.Thread.run(Thread.java:764)
Run Code Online (Sandbox Code Playgroud)

仅当安装 .apk 时才会发生这种情况。如果我从 Android Studio 运行该应用程序,一切都很好。

Eva*_*ror 7

我相信您需要编辑proguard-rules.pro文件以将这些数据类包含在这一行中。你可以在这里读更多关于它的内容。

-keepclassmembers,allowobfuscation class * {
    @com.google.gson.annotations.SerializedName <fields>;
}
Run Code Online (Sandbox Code Playgroud)