spring-bootkotlinjacksonobjectmapperjackson-modules

Jackson + KotlinModule: Conflicting/ambiguous property name definitions (implicit name 'isFoo')


Stumbling through a strange behaviour in Jackson when used with KotlinModule. Trying to deserialize a JSON object with isXxx-Boolean and xxx-none-Boolean property. Any solution how to deal with this?

    data class FooObject(
        @JsonProperty("isFoo")
        val isFoo: Boolean,
        @JsonProperty("foo")
        val foo: String,
    )

    @Test
    fun `deserialization should work` (){
        val serialized = """
            {
              "isFoo": true,
              "foo": "bar"
            }
        """.trimIndent()

        val objectMapper: ObjectMapper = Jackson2ObjectMapperBuilder()
            .modules(KotlinModule())
            .build()

        val deserialized = objectMapper.readValue(serialized, FooObject::class.java)

        assertNotNull(deserialized)
    }

throws 

Results in

java.lang.IllegalStateException: Conflicting/ambiguous property name definitions (implicit name 'isFoo'): found multiple explicit names: [isFoo, foo], but also implicit accessor: [method org.dnltsk.Test$FooObject#getFoo()][visible=true,ignore=false,explicitName=false], [method org.dnltsk.Test$FooObject#isFoo()][visible=true,ignore=false,explicitName=false]

By removing the @JsonProperty-annotations the exception turns to

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Duplicate creator property "isFoo" (index 0 vs 1) for type `org.dnltsk.Test$FooObject` 
 at [Source: (String)"{
  "isFoo": true,
  "foo": "bar"
}"; line: 1, column: 1]

Solution

  • Add the following annotation to the top of your data class:

    @JsonAutoDetect(
        getterVisibility = JsonAutoDetect.Visibility.NONE,
        isGetterVisibility = JsonAutoDetect.Visibility.NONE,
    )