In the previous lesson, you learned how to ignore unknown fields, and now you will see how to ignore null fields with Java Jackson.
We use the Jackson library in all the lessons since it is one of the most widely used Java library for working with JSON.
We have a User class:
class User { private String name; private int age; private String city; // constructors, getters, setters and toString() method... }
Let’s create one object of the User class and parse it to JSON using the ObjectMapper class:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; class Test { public static void main(String[] args) throws IOException { ObjectMapper objectMapper = new ObjectMapper(); // creating a User object and populating only "name" and "age" User user = new User(); user.setName("Steve"); user.setAge(31); JsonNode userAsJson = objectMapper.convertValue(user, JsonNode.class); System.out.println(userAsJson.toPrettyString()); } }
How to ignore null fields with Java Jackson
We can tell Jackson to ignore null fields by adding the “@JsonInclude(JsonInclude.Include.NON_NULL)” annotation above the class declaration.
Here is an example:
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.annotation.JsonInclude; @JsonInclude(JsonInclude.Include.NON_NULL) 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(); // creating a User object and populating only "name" and "age" User user = new User(); user.setName("Steve"); user.setAge(31); JsonNode userAsJson = objectMapper.convertValue(user, JsonNode.class); System.out.println(userAsJson.toPrettyString()); } }
class User { private String name; private int age; @JsonInclude(JsonInclude.Include.NON_NULL) // ignore null only for this field private String city; // constructors, getters, setters and toString() method... }
Another way is to configure the ObjectMapper to omit the null fields like this:
ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
That was all about setting up Jackson to ignore null fields. In the next lesson, we will see how to convert a JSON array to a Java List.
Happy coding!