@SerializedName not working with Proguard

Viewed 524

On minifyEnabled true on a project with Proguard the ApiError class is not parsed correctly while using Gson.

data class ApiResponse<D>(
    @SerializedName("status") @Expose val status: String,
    @SerializedName("data") @Expose val data: D?,
    @SerializedName("error") @Expose val error: ApiError?
)

data class ApiError(
    @SerializedName("code") @Expose val code: Int,
    @SerializedName("message") @Expose val msg: String,
    @SerializedName("title") @Expose val title: String?
)

The following code gives an ApiResponse object where ApiError is not properly parsed.

val collectionType = object : TypeToken<ApiResponse<User>?>() {}.type
                        val gson = GsonBuilder()
                        val errorBody: ApiResponse<T> = gson.create().fromJson(stringObj, collectionType)

Adding @Keep on ApiError solves the issue but shouldn't @SerializedName do the same? Interestingly every field of ApiResponse is parsed properly. We have the same proguard rules as this one

1 Answers

If you want your models still being obfuscated use annotation @SerializedName("name_of_json_key"). It will let gson know the real name of the field.

-keepattributes *Annotation* in your proguard-rules.pro file. that will keep your annotations from obfuscation

Related