Search code examples
kotlinjacksonjackson-databind

Why doesn't setting DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES to false work on a jacksonObjectMapper?


I want to configure Jackson to ignore unknown properties via a mapper rather than annotations, but I can't get it to work. Here's a failing test. It should pass because I've configured the mapper to ignore unknown properties, but it fails as the json contains an unknown property (make). The second tests passing using the annotation.

package paul.demo.training

import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe



class JsonIgnore: FunSpec({

    test("Mapper should ignore unknown properties - mapper") {

        data class Car(val colour : String)
        val json = """
            { "colour" : "Red",
              "make" : "Ford"
            }
        """.trimIndent()

        val mapper = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,false)

        val car = mapper.readValue(json,Car::class.java)

        car.colour shouldBe "Red"
    }

    test("Mapper should ignore unknown properties - annotation") {
        @JsonIgnoreProperties(ignoreUnknown = true)
        data class Car(val colour : String)
        val json = """
            { "colour" : "Red",
              "make" : "Ford"
            }
        """.trimIndent()

        val mapper = jacksonObjectMapper().configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,false)

        val car = mapper.readValue(json,Car::class.java)

        car.colour shouldBe "Red"
    }
})

Solution

  • It should pass because I've configured the mapper to ignore unknown properties

    You haven't configured it this way. You have set it so that it doesn't fail on IGNORED properties, not on UNKNOWN properties. So without setting your model to ignore the unknown properties (which you do in the second test), it's expected that your test fails.

    I think you wanted to set FAIL_ON_UNKNOWN_PROPERTIES, not FAIL_ON_IGNORED_PROPERTIES to false.