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

2023-12-22

我有一个字段,我想根据该 Json 对象上的值将其反序列化为密封子类的实例。

[
  {
    "id": 1L,
    "some_array": [],
    "my_thing": {
      "type": "sealed_subclass_one",
      "other_thing": {
        "thing": "thing is a string"
      }
    }
  }, {
    "id": 2L,
    "some_array": [],
    "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
)

我的密封班级

@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:sealed_subclass_one 未在类 com.myapp.MyResponse 范围内注册多态序列化

有没有一种简单的方法来注册值type这样就可以在没有自定义序列化器的情况下进行反序列化?


我相信如果你改变@SerialName("type") to @SerialName("sealed_subclass_one")(同样对于SealedSubclassTwo声明)它应该能够找到正确的序列化器。

The SerialName密封子类型上的属性是为了关联 json 的内容type具有适当子类的属性(以及适当的序列化器实例)。

See https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#a-bit-of-customizing https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#a-bit-of-customizing更多细节。但该文档的相关部分是:

默认情况下,编码类型名称等于类的完全限定名称。 要改变这一点,您可以使用 @SerialName 注释来注释该类

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据字段值反序列化为密封子类 的相关文章

随机推荐