2

@JsonIgnoreProperties(ignoreUnknown = true)Ktor アプリで Kotlinx シリアライゼーションを使用しており、Jacksonsアノテーションに相当するものを探しています。私は知っている

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

注釈付きのクラスがいくつかあります@Serializable。Jackson でできるように、ignoreUnknownKeys を 1 つの型クラス/型のみに適用する方法はありますか?

4

1 に答える 1

1

次のトリックを実行できます。

  1. Ktor に渡す format インスタンスのignoreUnknownKeysプロパティ ( false) のデフォルト値を保持します。Json
  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 }))
        }
    })
}
于 2021-03-29T17:43:13.203 に答える