This quick tutorial is going to cover how to ignore unknown properties or new fields in Jackson. It is necessary for situations which we encounter unknown JSON properties that can not bind to existing Java objects, but we need to allow such properties in input because either we don’t know all properties there could be, or we are only interested in subset of properties anyway.

1. Ignore Unknown Properties Per-class

To ignore unknown properties or new fields in Jackson at per-class level, we can use the @JsonIgnoreProperties. The annotation allows us to:

  • Ignore specified list of properties for the annotated class, or
  • Ignore any unknown properties or new fields for annotated classes (property ignoreUnknown, set to true)

Let’s see an example which we use the @JsonIgnoreProperties annotation to ignore any unknown properties or new fields in JSON input without exception:

Or we just want to ignore the specified list of properties: qty, rating.

2. Ignore Unknown Properties in Jackson Globally

It is also possible to ignore unknown properties or new fields in Jackson globally. To do this, we just need to disable the FAIL_ON_UNKNOWN_PROPERTIES feature of the ObjectMapper object.

Let’s see an example that we ignore two unknown properties: qty, rating existing in the Json string but not in the Book object:

2.1. Configure Jackson ObjectMapper in Spring Boot

In Spring Boot applications that use Jackson, we can customize the ObjectMapper’s behaviors in the file or by using the environment, for example:

3. Using @JsonAnySetter to Ignore Unknown Properties

To ignore unknown properties in Jackson, another approach we can do is to define a 2-argument method annotated with theĀ @JsonAnySetter to be called whenever otherwise unknown property is encountered, like so:

Note that if so, this method will be called once per unknown property.

4. Conclusion

The tutorial has just illustrated us how to ignore unknown properties or new fields in Jackson by different approaches, from per-class level to global level and we can choose the appropriate approaches depends on our purpose.

The implementation of all examples in this tutorial can be found on my Github project. This is an Maven based project, so it should be easy to import into any IDEs like Eclipse, Intellij, etc.

Here are some related tutorials:

Ignore or Exclude Field in Gson

Convert Java Object to Json and Vice Versa

0 0 vote
Article Rating