Ignore Unknown JSON Fields in Java Jackson

In this lesson, you will learn how to set up Jackson to ignore unknown JSON fields.

For example, if we have a JSON like this one:

{
  "name": "Tom",
  "age": 25,
  "city": "London",
  "membershipType": "golden"
}

And the following User class:

class User {

  private String name;
  private int age;
  private String city;

  //Constructors, getters, setters and toString() method
}

Note: We need the default constructor, getters, and setters methods for the Jackson conversion.

Jackson maps the fields by matching the names of the JSON fields to the getter and setter methods in the Java object.

You see that in the User class we don’t have a field “membershipType”.

Let’s try to convert the above JSON to the User object:

import com.fasterxml.jackson.databind.ObjectMapper;

class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    String json = "{\"name\": \"Tom\", \"age\": 25, \"city\": \"London\", \"membershipType\": \"golden\"}";

    User user = objectMapper.readValue(json, User.class);

    System.out.println("User object: " + user);
  }
}
Exception in thread “main” com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field “membershipType” (class com.example.demo.User), not marked as ignorable…
 
As you can see, we got the UnrecognizedPropertyException because we didn’t set the field “membershipType” to be ignored during the conversion.

How to ignore unknown JSON Fields?

To successfully convert a JSON to the User object, we need to say to Jackson to ignore all fields from the JSON that are not present in the User class.

We can do that by placing the annotation “@JsonIgnoreProperties(ignoreUnknown = true)” above the class declaration,  which will fix the above error.

@JsonIgnoreProperties(ignoreUnknown = true)
class User {

  private String name;
  private int age;
  private String city;

  //Constructors, getters, setters and toString() method
}

class Test {

  public static void main(String[] args) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();

    String json = "{\"name\": \"Tom\", \"age\": 25, \"city\": \"London\", \"membershipType\": \"golden\"}";

    User user = objectMapper.readValue(json, User.class);

    System.out.println("User object: " + user);
  }
}
User object: User{name=’Tom’, age=25, city=’London’}
 
The conversion went well, Jackson ignored the unknown JSON fields, and we got the User object populated with the corresponding values.
 
Another way is to configure the ObjectMapper to ignore the unknown JSON fields like this:
 
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

That’s it!

Leave a Reply

Your email address will not be published.