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?
Jackson API provides two ways to ignore unknown fields, first at the class level using @JsonIgnoreProperties annotation and second at the ObjectMapper level using configure() method.
Alternatively, you can also use @JsonIgnoreProperties annotation to ignore undeclared properties. The @JsonIgnoreProperties is a class-level annotation in Jackson and it will ignore every property you haven't defined in your POJO.
If the JSON string consists of properties that cannot be mapped to java class attributes, then we encounter UnrecognizedPropertyException.
Ignore Fields Using Filters Finally, we can also use filters to ignore specific fields in Jackson. First, we need to define the filter on the Java object: @JsonFilter("myFilter") public class MyDtoWithFilter { ... }
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 of fasterxml.jackson
.
Pay attention of the version not only of @JsonProperty
, etc, but also the version of Jackson you use when importing ObjectMapper
and DeserializationFeature
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With