根据字段值反序列化为密封的子类

我有一个字段要基于该Json对象上的值反序列化为密封子类的实例。

[
  {
    "id": 1L,"some_array": [],"my_thing": {
      "type": "sealed_subclass_one","other_thing": {
        "thing": "thing is a string"
      }
    }
  },{
    "id": 2L,"my_thing": {
      "type": "sealed_subclass_two","other_thing": {
        "other_thing": "other_thing is a string too"
      }
    }
  },]

响应模型:

@Serializable
data class MyResponse(
  @SerialName("id") 
  val id: Long

  @SerialName("some_array") 
  val someArray: Array<Something>

  @SerialName("my_thing") 
  val myThing: MySealedClassResponse
)

MySealedClass

@Serializable
sealed class MySealedClassResponse : Parcelable {
    @Serializable
    @SerialName("type")
    data class SealedSubclassOne(
        val thing: String
    ) : MySealedClassResponse()

    @Serializable
    @SerialName("type")
    data class SealedSubclassTwo(
        val otherThing: String
    ) : MySealedClassResponse()
}

就目前而言,我遇到了序列化异常,因为序列化器不知道该怎么做:

kotlinx.serialization.SerializationException:对于com.myapp.MyResponse类范围内的多态序列化,未注册seal_subclass_one

是否有一种简单的方法来注册type的值,以便不需要自定义序列化程序就可以进行反序列化?

CURRY8888 回答:根据字段值反序列化为密封的子类

我相信,如果将@SerialName("type")更改为@SerialName("sealed_subclass_one")(对于SealedSubclassTwo声明同样如此),它应该能够找到正确的序列化程序。

密封子类型上的SerialName属性是将json的type属性与适当的子类(以及适当的序列化程序实例)相关联的外观。

有关更多详细信息,请参见https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#a-bit-of-customizing。但是该文档的相关部分是:

默认情况下,编码类型名称等于类的完全限定名称。 要更改此设置,您可以使用@SerialName批注对类进行批注

本文链接:https://www.f2er.com/2768270.html

大家都在问