如何使用 kotlinx.serialization 拦截反序列化

How to intercept deserialisation with kotlinx.serialization

比如我有JSON

{
  "url": "//n.ya.com"
}

为了反序列化,我定义数据class

@Serializable
data class Foo(
    @SerialName("url")
    val link: String,
)

反序列化 Foo 对象后

foo.link"//n.ya.com"

如何在反序列化过程中删除 //,这意味着 foo.link"n.ya.com"

您可以为单个 属性 添加 custom Serializer:

@Serializable
data class Foo(
    @SerialName("url")
    @Serializable(with = FooLinkDeserializer::class)
    val link: String,
)

object FooLinkSerializer : KSerializer<String> {
    override val descriptor = PrimitiveSerialDescriptor("Foo.link", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder): String {
        return decoder.decodeString().substringAfter("//")
    }

    override fun serialize(encoder: Encoder, value: String) {
        encoder.encodeString("//$value")
    }
}

或者您可以 intercept JSON transformations 使用 JsonTransformingSerializer:

@Serializable
data class Foo(
    @SerialName("url")
    @Serializable(with = FooLinkInterceptor::class)
    val link: String,
)

object FooLinkInterceptor : JsonTransformingSerializer<String>(String.serializer()) {
    override fun transformDeserialize(element: JsonElement): JsonElement {
        return JsonPrimitive(element.jsonPrimitive.content.substringAfter("//"))
    }
}