【问题标题】:Deserializing into sealed subclass based on value of field根据字段值反序列化为密封子类
【发布时间】:2020-05-01 17:32:20
【问题描述】:

我有一个字段,我想根据该 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 的值,以便在没有自定义序列化程序的情况下进行反序列化?

【问题讨论】:

  • 嗨。如果您能提供您的最终解决方案代码,我将不胜感激

标签: kotlin kotlinx.serialization


【解决方案1】:

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

sealed 子类型上的 SerialName 属性是为了将 json 的 type 属性与适当的子类(以及相应的序列化程序实例)相关联。

请参阅https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#a-bit-of-customizing 了解更多详情。但该文档的相关部分是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-21
    • 2019-04-20
    • 1970-01-01
    • 2021-12-14
    • 2019-09-19
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多