kotlinjacksonjackson-databind

Using Jackson Databind @JsonAnySetter in version 2.17+?


I suspect that the behavior of the @JsonAnySetter in the jackson databind project has changed between version 2.15 and 2.17. Let's say I have this class in Kotlin:

@JsonIgnoreProperties(ignoreUnknown = true)
data class MyDTO(val type: String, @JsonAnySetter val otherContent: Map<String, String> = HashMap())

In version 2.15 (com.fasterxml.jackson.core:jackson-databind:jar:2.15.4), I could do this:

val objectMapper = jacksonObjectMapper()

val myDTO = objectMapper.readValue<MyDTO>(
    """{
    "type": "Hello",
    "key1": "value1",
    "key2": "value2"
}"""
)

println(myDTO)

This would print:

MyDTO(type=Hello, otherContent={key1=value1, key2=value2})

However, if I upgrade to 2.17.1 (com.fasterxml.jackson.core:jackson-databind:jar:2.17.1) the very same code would result in:

MyDTO(type=Hello, otherContent={})

As you can see, otherContent is now empty.

Has the behavior of @JsonAnySetter changed? What should I change to make the code behave the same in version 2.17?


Solution

  • Yeah this stuck me for a while too. It turns out that it has indeed changed, see https://github.com/FasterXML/jackson-databind/issues/4508

    They explain it better, but the gist is you need to do @field:JsonAnySetter on your parameter, because 2.17+ annotates the wrong underlying property now and you need to tell it to behave.