Cannot parse json objects with GSON when setting minifyEnabled is true

Issue

When I use

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

everything works perfectly.

But if change to

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

I get a parsing error.

My classes for parse:

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
)

Here I use gson:

val searchResponse = Gson().fromJson(jsonObject.toString(), SearchResponse::class.java)

In proguard-rules.pro I have one non-comment line -keepattributes *Annotation*

I would be grateful for any help!

EDIT
Error log:

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)

This happens only with .apk installation. If I run the app from Android Studio all is fine.

Solution

I believe that you need to edit your proguard-rules.pro file to include those data classes with this line. You can read more about it here.

-keepclassmembers,allowobfuscation class * {
    @com.google.gson.annotations.SerializedName <fields>;
}

Answered By – Evans Chepsiror

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published