Jackson Ignore null fields

Suppose you have a java class as below

public class Employee {
  private String fname;

  private String lname;

  private int id;

  // getter and setter methods
}

Its object is created with values “John”, null and 123 for fname, lname and id fields respectively.

Now, when this object is serialized or converted to json using Jackson ObjectMapper, the resultant string will be

{“fname”: “John”, “lname”: null, “id”: 123}

In this article, we will understand how to ignore or remove fields with null value from json response with Jackson ObjectMapper in java.
This means that fields with null values will not be a part of json string.

Ignore specific fields
Jackson provides @JsonInclude annotation with value attribute set to Include.NON_NULL. This means that only fields with non-null values will be included while preparing json string.

This annotation can be applied over fields for which this configuration is required. Example,

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

public class Employee { 

  private String fname; 

  @JsonInclude(value = Include.NON_NULL)
  private String lname; 

  private int id; 
  
  // getter and setter methods 
}

With this annotation in place, object serialized with null value for this field will produce below response

{“fname”: “John”, “id”: 123}

Remember that if any other field is null, it will still be included in the json string.
Ignore all null fields
If you wish to remove all null fields from json string, then apply @JsonInclude over the class as below

import com.fasterxml.jackson.annotation.JsonInclude; 
import com.fasterxml.jackson.annotation.JsonInclude.Include; 

@JsonInclude(value = Include.NON_NULL) 
public class Employee { 

  private String fname; 

  private String lname; 

  private int id; 

  // getter and setter methods 
}

Now, any null field will not be a part of json response.

ObjectMapper configuration
If you do not have access to the source code of the class, then annotation can not be used.
For such case, Jackson ObjectMapper provides a configuration to ignore null fields as given below

ObjectMapper mapper = new ObjectMapper();
// ignore null fields
mapper.setSerializationInclusion(Include.NON_NULL);
Employee e = new Employee();
e.setFname("John");
e.setId(123);
StringWriter writer = new StringWriter();
try { 
  mapper.writeValue(writer, l);
  System.out.println(writer.toString());
} catch (IOException e) {
  e.printStackTrace();
}

Json string is

{“fname”: “John”, “id”: 123}

Note that with this configuration, you cannot ignore a specific field. All null fields will be ignored.

Hope the article was useful.