首页 > 解决方案 > IgnoreUnknownKeys 仅适用于 Kotlinx 和 Ktor 的一种类型

问题描述

我在 Ktor 应用程序中使用 Kotlinx 序列化,并寻找相当于 Jacksons@JsonIgnoreProperties(ignoreUnknown = true)注释。我知道

install(ContentNegotiation) {
     json(Json{ ignoreUnknownKeys = true })
 }

我有一些类注释@Serializable。有没有办法只将 ignoreUnknownKeys 应用于一种类型类/类型,就像我可以对杰克逊做的那样?

标签: kotlinktorkotlinx

解决方案


您可以执行以下技巧:

  1. ignoreUnknownKeys保留格式实例的属性 ( false) 的默认值Json,您提供给 Ktor。
  2. 对于您希望以特殊方式处理的特定类,请创建额外的自定义序列化程序,它将在后台使用另一个格式实例。
  3. 将这些序列化程序连接到Json格式实例,您将提供给 Ktor。

为方便起见,您可以为 定义以下扩展函数KSerializer<T>

fun <T> KSerializer<T>.withJsonFormat(json: Json) : KSerializer<T> = object : KSerializer<T> by this {
    override fun deserialize(decoder: Decoder): T {
        // Cast to JSON-specific interface
        val jsonInput = decoder as? JsonDecoder ?: error("Can be deserialized only by JSON")
        // Read the whole content as JSON
        val originalJson = jsonInput.decodeJsonElement().jsonObject
        return json.decodeFromJsonElement(this@withJsonFormat, originalJson)
    }
}

用法:

install(ContentNegotiation) {
    json(Json {
        serializersModule = SerializersModule {
            contextual(MyDataClass.serializer().withJsonFormat(Json { ignoreUnknownKeys = true }))
        }
    })
}

推荐阅读