In a perfect world, the consumer and producer of an API would always be in lockstep, only changing with each other and adhering to the strictest of contracts. Alas, we live in the real world, and it helps to be a bit pessimistic when controlling data falls just outside of your grasp.
在理想的情况下,API的消费者和生产者将始终处于同步状态,彼此之间只会相互更改并遵守最严格的合同。 las,我们生活在现实世界中,当控制数据超出您的掌握范围时,它会有些悲观。
If you are the consumer of an API, sometimes there might be a reasonable fallback if deserialization goes horribly wrong. In other words, we want a KSerializer that will fall back to some default value if deserialization fails:
如果您是API的使用者,则如果反序列化严重错误,有时可能会有一个合理的回退。 换句话说,我们希望KSerializer在反序列化失败时会回落到一些默认值:
fun <T> KSerializer<T>.fallback(value: T) = object : KSerializer<T> by this {
override fun deserialize(decoder: Decoder): T {
check(decoder is JsonInput) {
"This deserializer only supports deserializing JSON"
}
return try {
decoder.json.fromJson(this@fallback, decoder.decodeJson())
} catch (exception: Exception) {
// Deserialization failed! Falling back, but you should
// log the exception in case it shouldn't be happening.
value
}
}
}This extension of KSerializer is modeled heavily after KSerializer.nullable: it augments an existing KSerializer with a bit of extra functionality. In this case, we wrap the deserialization call in a try/catch, returning the provided default value if any exception occurred during deserialization.
KSerializer此扩展在KSerializer之后进行了大量KSerializer.nullable :它通过一些额外的功能增强了现有的KSerializer 。 在这种情况下,我们将反序列化调用包装在try/catch ,如果反序列化期间发生任何异常,则返回提供的默认value 。
Now, putting it to use: for forwards-compatibility reasons, it can be helpful to allow enums to take a default UNKNOWN value. Like the name suggests, we want any unknown value to be turned into UNKNOWN instead of causing an error:
现在,将其投入使用:由于前向兼容的原因,允许枚举采用默认的UNKNOWN值可能会有所帮助。 顾名思义,我们希望将任何未知值转换为UNKNOWN而不是导致错误:
@Serializable
enum class TestEnum {
UNKNOWN, ALPHA, BETA, GAMMA, DELTA
}
val fallbackSerializer = TestEnum.serializer().fallback(TestEnum.UNKNOWN)With the fallback serializer above, that’s all there is to it!
有了上面的后备序列化器,就足够了!
Alex works atLivefront, where we always try to leave data a little bit cleaner than when we get it.
亚历克斯(Alex)在 Livefront工作 ,在这里,我们总是尽力使数据比获取时干净一些。
翻译自: https://medium.com/livefront/kotlinx-serialization-json-deserializer-with-a-fallback-79dd6e9d471f