Search code examples
androidkotlingsonretrofit2proguard

Data class gson error when minify is enabled


So, I have a Kotlin data class used as a data transfer object with the Retrofit library, as follows:

data class GenericPaginationResponse<T>(
@SerializedName("data")
val data: List<T>,
@SerializedName("pagination")
val pagination: PaginationResponse
)

However, when I minify the application, it encounters an error when executed with the following message:

Unable to invoke no-args constructor for class com.lelestacia.network.model.GenericPaginationResponse. Registering an InstanceCreator with Gson for this type may fix this problem.

I am using this data class in the network module of an Android project with a multi-module architecture. Here is the repository : Github Repository

Here is my proguard:

# If you keep the line number information, uncomment this to
# hide the original source file name.
-renamesourcefileattribute SourceFile

 # Keep generic signature of Call, Response (R8 full mode strips signatures from non-kept items).
 -keep,allowobfuscation,allowshrinking interface retrofit2.Call
 -keep,allowobfuscation,allowshrinking class retrofit2.Response

 # With R8 full mode generic signatures are stripped for classes that are not
 # kept. Suspend functions are wrapped in continuations where the type argument
 # is used.
 -keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation

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

 -keep class <1> {
   <init>();
 }

Solution

  • In your Network module there is file consumer-rules.pro

    Add below code

    -keep class com.lelestacia.network.model.*
    -keep class com.lelestacia.network.model.anime.*
    

    Also in your build.gradle of network module in release build type, add below code

    proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'consumer-rules.pro'
    

    You can follow below link for consumer-rules vs proguard-rules https://stackoverflow.com/a/60862591/8007341