Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Kotlin 基于字段值反序列化为密封子类_Kotlin_Kotlinx.serialization - Fatal编程技术网

Kotlin 基于字段值反序列化为密封子类

Kotlin 基于字段值反序列化为密封子类,kotlin,kotlinx.serialization,Kotlin,Kotlinx.serialization,我有一个字段,我想根据Json对象上的值反序列化为一个密封子类的实例 [ { "id": 1L, "some_array": [], "my_thing": { "type": "sealed_subclass_one", "other_thing": { "thing": "thing is a string" } } }, { "id": 2L, "some_array": [],

我有一个字段,我想根据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
)
目前,我收到一个序列化异常,因为序列化程序不知道该做什么:

kotlinx.serialization.SerializationException:密封的_子类_one未在com.myapp.MyResponse类的作用域中注册多态序列化


有没有一种简单的方法来注册
type
的值,以便在没有自定义序列化程序的情况下进行反序列化?

我相信如果您将
@SerialName(“type”)
更改为
@SerialName(“sealed\u subclass\u one”)
(对于
sealedsubclass\u-one>声明也是如此)它应该能够找到正确的序列化程序

密封子类型上的
SerialName
属性是它用来将json的
type
属性与适当的子类(以及相应的序列化程序实例)关联起来的

有关更多详细信息,请参阅。但该文件的相关部分是:

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

@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()
}