Android中Gson反序列化kotlinx ImmutableList遇R8报错,求缺失规则
问题:R8开启后Gson反序列化ImmutableList抛出数组越界异常
在Android项目中,我尝试使用Gson反序列化kotlinx.collections库的ImmutableList,因项目限制暂无法使用Kotlin序列化。自定义的JsonDeserializer代码如下:
class ImmutableListDeserializer : JsonDeserializer<ImmutableList<*>> { @Throws(JsonParseException::class) @Suppress("UnstableApiUsage") override fun deserialize( json: JsonElement, type: Type, context: JsonDeserializationContext ): ImmutableList<*> { val typeArguments = (type as ParameterizedType).actualTypeArguments val parameterizedType: Type = listOf<Any>(typeArguments[0]).type val list = context.deserialize<List<*>>(json, parameterizedType) return list.toImmutableList() } @Suppress("UnstableApiUsage", "UNCHECKED_CAST") private fun <E> listOf(arg: Type): TypeToken<List<E>> = object : TypeToken<List<E>>() {} .where(object : TypeParameter<E>() {}, TypeToken.of(arg) as TypeToken<E>) }
该反序列化器通过registerTypeAdapter(ImmutableList::class.java, ImmutableListDeserializer())添加至GsonBuilder。在未激活R8的Debug变体中运行正常,但**开启R8(AGP 8.0起默认全模式)**后,调用gson.fromJson(json, DataClassContainingImmutableList::class.java)时抛出如下错误:
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 at com.myapp.serialization.ImmutableListDeserializer.deserialize(ImmutableListDeserializer.kt:21) ...
错误位于val parameterizedType: Type = listOf<Any>(typeArguments[0]).type行,原因是typeArguments数组长度为0,无法访问索引0。
我已添加Gson官方示例中的Proguard/R8规则,以及针对自定义反序列化器中Guava类的额外规则:
-keep,allowobfuscation,allowshrinking class com.google.common.reflect.TypeToken { *; } -keep,allowobfuscation,allowshrinking class * extends com.google.common.reflect.TypeToken -keep,allowobfuscation,allowshrinking class com.google.common.reflect.TypeParameter { *; } -keep,allowobfuscation,allowshrinking class * extends com.google.common.reflect.TypeParameter
请问缺少哪条R8规则导致该问题?
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

