kotlin - IgnoreUnknownKeys 仅适用于 Kotlinx 和 Ktor 的一种类型
问题描述
我在 Ktor 应用程序中使用 Kotlinx 序列化,并寻找相当于 Jacksons@JsonIgnoreProperties(ignoreUnknown = true)
注释。我知道
install(ContentNegotiation) {
json(Json{ ignoreUnknownKeys = true })
}
我有一些类注释@Serializable
。有没有办法只将 ignoreUnknownKeys 应用于一种类型类/类型,就像我可以对杰克逊做的那样?
解决方案
您可以执行以下技巧:
ignoreUnknownKeys
保留格式实例的属性 (false
) 的默认值Json
,您提供给 Ktor。- 对于您希望以特殊方式处理的特定类,请创建额外的自定义序列化程序,它将在后台使用另一个格式实例。
- 将这些序列化程序连接到
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 }))
}
})
}
推荐阅读
- r - 在 R 中分离数据
- javascript - JS:chrome 开发工具中对 JS 文件的更改未反映
- android - Glide 和 Picasso 无法从 YouTube 加载图像
- php - 是否可以将函数存储在数组中并根据 if 语句结果调用它们?
- powershell - “AND”没有按预期运行
- python - 传递 1 2 23 32 4 在 python 的 max 函数中返回 4,为什么?
- google-cloud-platform - 使用 google_cloud_scheduler_job 调度批处理作业
- rust - 如何为函数实现特征
- regex - 使用 Perl 读取模式匹配之间的所有行
- cuda - 支持 `__shfl()` 和 `__shfl_sync()` 指令的正确方法是什么?