在反序列化时使用 gson 定义嵌套列表类型

问题描述 投票:0回答:1

通过使用新的 AGP v8.0 并启用完整的 R8,当我尝试从 JSON 字符串反序列化嵌套对象时,嵌套对象的类型被 gson 错误地识别为 LinkedTreeMap。

actions_list.json:

    [
    {
    "name": "actionList1",
    "listA": [
      {
        "name": "action1"
      },
      {
        "name": "action2"
      }
    ] // end of listA
    }, // end of actionList1
    ... // actionList1 to actionListN
    ]

动作类:

    data class Action(
    @SerializedName("name") @Expose val name: String,
    val actions: List<MyAction>,
    var a: Int,
    ...
    var n: Boolean,
    )

MyActions.kt:

    data class MyActions(
    @SerializedName("name")
    val name: String,
    var state: MyActionState?
    )

MyActionState.kt:

    enum class MyActionState{
    Nothing, Running, Done, Failed, Deactivate
    }

proguard-rules.pro:

    -keepattributes Signature, InnerClasses, EnclosingMethod
    -keepattributes RuntimeVisibleAnnotations, RuntimeVisibleParameterAnnotations
    -dontwarn javax.annotation.**
    -dontwarn kotlin.Unit
    -dontwarn retrofit2.KotlinExtensions
    -dontwarn retrofit2.KotlinExtensions$*
    -dontwarn okhttp3.**
    -keep class okhttp3.** { *;}
    -dontwarn okio.**
    -keepattributes SourceFile,LineNumberTable
    -keep class com.google.gson.*
    -keep interface com.google.gson.*
    -keep class * extends com.google.gson.reflect.TypeToken
    -keep public class * implements java.lang.reflect.Type
    -keep class path.to.all.app.class
    -keep interface path.to.all.app.class
    -keep enum path.to.all.app.class
    -keepattributes *Annotation*
    -keepattributes AnnotationDefault
    -keepattributes Signature

这就是我如何将 json 数组转换为列表:

    val jsonString: String = this.assets.open("actions/actions_list.json")
    .bufferedReader()
    .use { it.readText() }
    
    val type = TypeToken.getParameterized(List::class.java,Action::class.java).type
    
    return Gson().fromJson(jsonString, type )

app build.gradle中minifyEnabled为true时,List转换为LinkedTreeMap。我有太多嵌套对象,有没有什么办法可以在没有自定义 Desrializer 类、TypeConverters、禁用完整 r8 模式和降级 gradle 版本的情况下解决这个问题?

serialization android-gradle-plugin gson proguard android-r8
1个回答
0
投票

将这些行添加到 proguard-rules.pro 解决了问题:

-keepclassmembernames class path.to.MyActions {<fields>;}
-keepclassmembernames class path.to.Action{<fields>;}
© www.soinside.com 2019 - 2024. All rights reserved.