我有一个字段要基于该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
的值,以便不需要自定义序列化程序就可以进行反序列化?