如何在kotlinx.serialization反序列化JSON时区分{data: null}和{}?
@Serializable
class MyClass(val data: String?)发布于 2021-05-25 19:59:12
您需要一个自定义设置器和一个私有布尔字段来指示字段值是否被触及。所以,就像:
@Serializable
class MyClass {
private var isDataTouched = false
val data: String
set(value) {
field = value
isDataTouched = true
}
}注意,不能在默认构造函数中定义字段。
发布于 2021-05-26 12:21:22
您可以利用多态和JsonContentPolymorphicSerializer来区分您正在反序列化的响应类型:
@Serializable(with = MyResponseSerializer::class)
sealed class MyResponse
@Serializable
class MyEmptyClass : MyResponse()
@Serializable
class MyClass(val data: String?) : MyResponse()
// this serializer is reponsible for determining what class we will receive
// by inspecting json structure
object MyResponseSerializer : JsonContentPolymorphicSerializer<MyResponse>(MyResponse::class) {
override fun selectDeserializer(element: JsonElement) = when {
"data" in element.jsonObject -> MyClass.serializer()
else -> MyEmptyClass.serializer()
}
}之后,使用MyResponse类反序列化,您将收到MyEmptyClass或MyClass。
val e = Json.decodeFromString<MyResponse>("""{}""") // returns MyEmptyClass object
val o = Json.decodeFromString<MyResponse>("""{"data": null}""") // returns MyClass object
println(Json.encodeToString(e)) // {}
println(Json.encodeToString(o)) // {"data": null}
// since sealed class is the parent we can have exhaustive when:
when(e) {
is MyClass -> TODO("handle response with data")
is MyEmptyClass -> TODO("handle empty response")
}https://stackoverflow.com/questions/67694640
复制相似问题