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); } }
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); } }
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
That’s it!