Wednesday, 28 October 2015

Jackson: Ignore Empty, null fields

You can ignore empty, null values in two ways.
a.   By configuring ObjectMapper
b.   By using JsonInclude annotation

a. By configuring ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_EMPTY);
Above statements are used to ignore empty fields, null values.

import java.util.ArrayList;
import java.util.List;

public class Employee {
 private int id;
 private String firstName;
 private String lastName;
 private List<String> hobbies = new ArrayList<>();

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.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;
 }

 public List<String> getHobbies() {
  return hobbies;
 }

 public void setHobbies(List<String> hobbies) {
  this.hobbies = hobbies;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [id=").append(id).append(", firstName=")
    .append(firstName).append(", lastName=").append(lastName)
    .append(", hobbies=").append(hobbies).append("]");
  return builder.toString();
 }

}


import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class Main {
 public static void main(String args[]) throws JsonGenerationException,
   JsonMappingException, IOException {
  Employee emp = new Employee();

  emp.setFirstName("Hari Krishna");
  emp.setId(1);
  emp.setLastName(null);

  ObjectMapper mapper = new ObjectMapper();
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.setSerializationInclusion(Include.NON_EMPTY);
  String json = mapper.writeValueAsString(emp);

  System.out.println(json);

 }
}


Output
{
  "id" : 1,
  "firstName" : "Hari Krishna"
}


b. By using JsonInclude annotation
By adding ‘@JsonInclude(Include.NON_EMPTY)’ annotation on top of the class you can exclude empty, null fields.

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

@JsonInclude(Include.NON_EMPTY)  
public class Employee {

}






Prevoius                                                 Next                                                 Home

No comments:

Post a Comment