Jackson Ignore Null and Empty Fields

By Arvind Rai, October 15, 2017
This page will walk through how to ignore Null and Empty fields using Jackson API. Jackson provides Include.NON_NULL to ignore fields with Null values and Include.NON_EMPTY to ignore fields with Empty values. By default Jackson does not ignore Null and Empty fields while writing JSON. We can configure Include.NON_NULL and Include.NON_EMPTY at property level as well as at class level using @JsonInclude annotation. To configure Include.NON_NULL and Include.NON_EMPTY globally for every class we need to do it at ObjectMapper level using its setSerializationInclusion() method. Here on this page we will provide complete examples to use Include.NON_NULL and Include.NON_EMPTY at property level with @JsonInclude annotation and using ObjectMapper to ignore Null and Empty fields globally. We will also provide examples to ignore Null and Empty values for a Map.

Gradle to Resolve Jackson API

Find the Gradle file to resolve Jackson API.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'Concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.9.1'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.1'
    compile group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.9.1'
} 

Include.NON_NULL and Include.NON_EMPTY

To ignore Null fields in JSON, Jackson provides Include.NON_NULL and to ignore Empty fields Jackson provides Include.NON_EMPTY.
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. Non-empty can have different meaning for different objects such as List with size zero will be considered as empty. In case of Map to check empty isEmpty() is called.

Include is an enum inside JsonInclude. Include has properties that are ALWAYS, NON_NULL, NON_ABSENT, NON_EMPTY, NON_DEFAULT, CUSTOM, USE_DEFAULTS. These properties can be used at property level, class level and we can configure globally using ObjectMapper. Find the sample code.

1. Using Include.NON_NULL and Include.NON_EMPTY at Property level

Find the code snippet.
public class Person {
    @JsonInclude(Include.NON_NULL)		
    private String city;
    @JsonInclude(Include.NON_EMPTY)	
    private String country;
    ------
}
If the value in city is null then it will not be included while writing JSON for Person object. In the same way if the value in country is empty then it will not be included in JSON.

2. Using Include.NON_NULL and Include.NON_EMPTY at Class level

Find the code snippet for Include.NON_NULL at class level.
@JsonInclude(Include.NON_NULL)
public class Person {
  ------
} 
Using Include.NON_NULL at class level means any property of this class having null value will not be included in JSON.
Now find the code snippet for Include.NON_EMPTY at class level.
@JsonInclude(Include.NON_EMPTY)	
public class Person {
  ------
}
Using Include.NON_EMPTY at class level means any property of this class having empty value will not be included in JSON.

3. Using Include.NON_NULL and Include.NON_EMPTY globally with ObjectMapper

Find the code snippet.
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setSerializationInclusion(Include.NON_EMPTY); 
In the above code we have configured ObjectMapper with Include.NON_NULL and Include.NON_EMPTY using setSerializationInclusion() that ignore Null and Empty values globally for every class. Now when we write JSON using mapper instance for any given object, then the properties of that object having null or empty value will not be included in JSON. For example if we want to write any object into JSON as string we will write code as following.
String jsonBook = mapper.writerWithDefaultPrettyPrinter()
        		 .writeValueAsString(book);
The output JSON will not include fields with Null and Empty values.

1. Example of Include.NON_NULL and Include.NON_EMPTY at Property Level

Find the example of Include.NON_NULL and Include.NON_EMPTY at property level.
Person.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
public class Person {
	private Integer id; 
	private String name;
	@JsonInclude(Include.NON_NULL)		
  	private String city;
	@JsonInclude(Include.NON_EMPTY)	
  	private String country;
  	public Person(){}
  	public Person(Integer id, String name, String city, String country){
  		this.id = id;
  		this.name = name;
  		this.city = city;
  		this.country = country;
  	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
} 
IgnoreNullEmptyAtPropertyLevel.java
package com.concretepage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class IgnoreNullEmptyAtPropertyLevel {
  public static void main(String[] args) throws JsonProcessingException {
       ObjectMapper mapper = new ObjectMapper();
       Person person = new Person(110, "Mohit", null, "");
       String jsonPerson = mapper.writerWithDefaultPrettyPrinter()
			 .writeValueAsString(person);
       System.out.println(jsonPerson);
  }
}
Output
{
  "id" : 110,
  "name" : "Mohit"
} 
Without Include.NON_NULL and Include.NON_EMPTY, output will be as following.
{
  "id" : 110,
  "name" : "Mohit",
  "city" : null,
  "country" : ""
} 

2. Example of Include.NON_NULL and Include.NON_EMPTY Globally with ObjectMapper

Find the example of Include.NON_NULL and Include.NON_EMPTY with ObjectMapper
Book.java
package com.concretepage;
public class Book {
	private Integer id; 
	private String name;
  	private String writer;
  	private String category;   
  	public Book(){}
  	public Book(Integer id, String name, String writer, String category) {
  		this.id = id;
  		this.name = name;
  		this.writer = writer;
  		this.category = category;
  	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getCategory() {
		return category;
	}
	public void setCategory(String category) {
		this.category = category;
	}
} 
IgnoreNullEmptyWithObjectMapper.java
package com.concretepage;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class IgnoreNullEmptyWithObjectMapper {
  public static void main(String[] args) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    Book book = new Book(101, "Spring", null, "");
    String jsonBook = mapper.writerWithDefaultPrettyPrinter()
		 .writeValueAsString(book);
    System.out.println(jsonBook);
  }
}  
Output
{
  "id" : 101,
  "name" : "Spring"
} 
Without Include.NON_NULL and Include.NON_EMPTY, output will be as following.
{
  "id" : 101,
  "name" : "Spring",
  "writer" : null,
  "category" : ""
} 

3. Example to Ignore Null and Empty Values for Map

Here we will provide two examples to ignore Null and Empty values for a Map.

Example-1: Find the example to write JSON of an object which have a property of Map type annotated with Include.NON_EMPTY.
Company.java
package com.concretepage;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
public class Company {
   private String name;
   @JsonInclude(Include.NON_EMPTY)
   private Map<String, String> employess; 
   public Company() {}
   public Company(String name, Map<String, String> employess) {
	   this.name = name;
	   this.employess = employess;
   }
   public String getName() {
	   return name;
   }
   public void setName(String name) {
	   this.name = name;
   }
   public Map<String, String> getEmployess() {
	   return employess;
   }
   public void setEmployess(Map<String, String> employess) {
	   this.employess = employess;
   }  
} 
IgnoreNullEmptyMap.java
package com.concretepage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class IgnoreNullEmptyMap {
  public static void main(String[] args) throws JsonProcessingException {
	 ObjectMapper mapper = new ObjectMapper();
	 List<Company> list = new ArrayList<>();
	 Map<String, String> map = new HashMap<>();
	 map.put("A11", "Mahesh");
	 Company company1 = new Company("AAAA", map);
	 list.add(company1);		 
	 Company company2 = new Company("BBBB", new HashMap<>());
	 list.add(company2);
	 Company company3 = new Company("CCCC", null);
	 list.add(company3);
	 String jsonCompany = mapper.writerWithDefaultPrettyPrinter()
			 .writeValueAsString(list);
	 System.out.println(jsonCompany);
  }
} 
Output
[ {
  "name" : "AAAA",
  "employess" : {
    "A11" : "Mahesh"
  }
}, {
  "name" : "BBBB"
}, {
  "name" : "CCCC"
} ] 
Without Include.NON_NULL and Include.NON_EMPTY, output will be as following.
[ {
  "name" : "AAAA",
  "employess" : {
    "A11" : "Mahesh"
  }
}, {
  "name" : "BBBB",
  "employess" : { }
}, {
  "name" : "CCCC",
  "employess" : null
} ] 

Example-2: Find the example to write JSON of Map instance using Include.NON_NULL and Include.NON_EMPTY with ObjectMapper.
IgnoreNullEmptyMapWithObjectMapper
package com.concretepage;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class IgnoreNullEmptyMapWithObjectMapper {
  public static void main(String[] args) throws JsonProcessingException {
     ObjectMapper mapper = new ObjectMapper();
     mapper.setSerializationInclusion(Include.NON_NULL);
     mapper.setSerializationInclusion(Include.NON_EMPTY);
     Map<String, String> map = new HashMap<>();
     map.put("A11", "Mahesh");
     map.put("A22", null);
     map.put("A33", "");
     String jsonMap = mapper.writerWithDefaultPrettyPrinter()
			 .writeValueAsString(map);
     System.out.println(jsonMap);
  }
} 
Output
{
  "A11" : "Mahesh"
} 
Without Include.NON_NULL and Include.NON_EMPTY, output will be as following.
{
  "A11" : "Mahesh",
  "A22" : null,
  "A33" : ""
} 

Reference

Enum JsonInclude.Include
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us