次のトリックを実行できます。
- Ktor に渡す format インスタンスの
ignoreUnknownKeys
プロパティ ( false
) のデフォルト値を保持します。Json
- 特別な方法で処理したい特定のクラスについては、内部で別のフォーマット インスタンスを使用する追加のカスタム シリアライザーを作成します。
- これらのシリアライザを
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 }))
}
})
}