Jackson @JsonProperty not working if property name not equal field name
This is often caused when the annotations of Jackson is of Jackson 1, but you want to use Jackson 2, as mentioned in many other questions.
In my case, in the project I have another dependency which was imported wrongly:
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
when I create the ObjectMapper
. I guess testcontainers
uses its own ObjectMapper
as its dependency and exposed it incorrectly; actually it is an older version. Not sure which is.
I change it to
import com.fasterxml.jackson.databind.ObjectMapper;
and all works now. This is what I call "first level dependency", not "dependency of dependency". In my gradle file it is version 2.3.
I mention this because:
I see other questions only mentioning the confusion between Jackson 1 and 2, not this of
testcontainer
. We just must ignore those not offasterxml.jackson
.Pay attention of the version not only of
@JsonProperty
, etc, but also the version of Jackson you use when importingObjectMapper
andDeserializationFeature
.
cane
Updated on June 11, 2022Comments
-
cane almost 2 years
I have following JSON
{ "known-name": "Zevs", "approximate-age": 320 }
And binding class
public class GodBinding { @JsonProperty("known-name") public String name; @JsonProperty("approximate-age") public int age; // constructors // getters & setters }
And followng maven dependencies 2.23.2 2.5.4
<dependencies> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>${jersey.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-json-provider</artifactId> <version>${jackson.version}</version> </dependency> </dependencies>
If I post such json then I have unexpected result with null's.
GodBinding [name=null, age=0]
If I use @JsonProperty without names and send JSON where property names equal field names
{ "name": "Zevs", "age": 320 }
then it's working fine
GodBinding [name=Zevs, age=320]
If somebody know, how to make @JsonProperty("name") on fields working correctly?