Apply Jackson coercion configuration feature to specified deserialization cases

1.4k Views Asked by At

There are some fields, which should be deserialized from String to Double. However, the general ObjectMapper configuration doesn't allow coercion of scalars: configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false)

Before Jackson coercion configuration feature implementation, this String -> Double conversion was done with a custom deserializer. For example:

data class SeriesFrameInputChannel(
    @JsonDeserialize(using = TestDeserializer::class)
    @JsonProperty("test_field")
    val testFieldForConvertion: Double
)

class TestDeserializer : StdDeserializer<Double>(Double::class.java) {
    override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Double {
        return _parseDoublePrimitive(p, ctxt)
    }
}

However, after the coercion config was introduced, the following error occurred:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot coerce String value ("2.2") to `double` value (but might if coercion using `CoercionConfig` was enabled)

The issue could be solved by adding the following lines to the ObjectMapper configuration:

coercionConfigFor(LogicalType.Integer)
   .setCoercion(CoercionInputShape.String, CoercionAction.TryConvert)

However, it will affect the deserialization behavior of other fields, not only testFieldForConvertion.

What is the appropriate way to apply Jackson coercion configuration to the specified field case(-s), in order to avoid the deserialization behavior changes for other fields?

0

There are 0 best solutions below