google / gson

A Java serialization/deserialization library to convert Java Objects into JSON and back
Apache License 2.0
23.16k stars 4.27k forks source link

GSON deserialization fails with ClassCastException: Cannot cast com.google.gson.internal.LinkedTreeMap to androidx.collection.ArrayMap #2655

Open nitinsethi86 opened 4 months ago

nitinsethi86 commented 4 months ago

Gson version

2.8.6

Java / Android version

JDM 17 and All Android versions.

Used tools

Description

We recently moved from AGP 8.0.2 to AGP 8.2.2.

We use gson version 2.8.6 with below set of proguard rules:

GSON 2.2.4 specific rules

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.

For using GSON @Expose annotation

-keepattributes EnclosingMethod

Gson specific classes

-keep class sun.misc.Unsafe { *; } -keep class com.google.gson.stream.* { ; }

Prevent R8 from leaving Data object members always null

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

Retain generic signatures of TypeToken and its subclasses with R8 version 3.0 and higher.

-keep,allowobfuscation,allowshrinking class com.google.gson.reflect.TypeToken -keep,allowobfuscation,allowshrinking class * extends com.google.gson.reflect.TypeToken

-if class * -keepclasseswithmembers class <1> {

(...); @com.google.gson.annotations.SerializedName ; } After upgrade, we have started seeing ClasscastException like below: java.lang.ClassCastException: Cannot cast com.google.gson.internal.LinkedTreeMap to androidx.collection.ArrayMap We can fix it either by using Map as TypeToken or moving to 8.0.77 R8 version. Is this a known issue? Do we need to update the R8 rules? I tried both the latest versions of R8 in 8.2, 8.1 series and both of them don't work. I tried the latest rules from Gson too. It didn't work. ## Expected behavior No exception is thrown and deserialization happens ## Actual behavior The classcastexception is thrown. # Reproduction steps 1. ... 2. ... # Exception stack trace java.lang.ClassCastException: Cannot cast com.google.gson.internal.LinkedTreeMap to androidx.collection.ArrayMap ``` ```
Marcono1234 commented 4 months ago

I tried the latest rules from Gson too. It didn't work.

Did you try the rules from https://github.com/google/gson/blob/main/gson/src/main/resources/META-INF/proguard/gson.pro? They will also be included automatically in the next Gson release.

A few questions: