How to ignore the null and empty fields using the Jackson library in Java?

JavaJSONObject Oriented ProgrammingProgramming

The Jackson is a library for Java and it has very powerful data binding capabilities and provides a framework to serialize custom java objects to JSON and deserialize JSON back to Java object. The Jackson library provides @JsonInclude annotation that controls the serialization of a class as a whole or its individual fields based on their values during serialization.

The @JsonInclude annotation contains below two values

  • Include.NON_NULL: Indicates that only properties with not null values will be included in JSON.
  • Include.NON_EMPTY: Indicates that only properties that are not empty will be included in JSON


import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class IgnoreNullAndEmptyFieldTest {
   public static void main(String[] args) throws JsonProcessingException {
      ObjectMapper mapper = new ObjectMapper();
      Employee employee = new Employee(115, null, ""); // passing null and empty fields
      String result = mapper.writeValueAsString(employee);
// Employee class
class Employee {
   private int id;
   private String firstName;
   private String lastName;
   public Employee(int id, String firstName, String lastName) {
      super(); = id;
      this.firstName = firstName;
      this.lastName = lastName;
   public int getId() {
      return id;
   public void setId(int id) { = id;
   public String getFirstName() {
      return firstName;
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   public String getLastName() {
   return lastName;
   public void setLastName(String lastName) {
      this.lastName = lastName;


 "id" : 115
Published on 27-Sep-2019 17:08:32