Wednesday 28 October 2015

Gson: Ignore null and empty fields

By default gson ignore null values as long as you don't set serializeNulls() to your GsonBuilder. One way to handle empty values is by implementing JsonSerializer.

Step 1: Implement JsonSerializer.
static class CollectionAdapter implements JsonSerializer<Collection<?>> {
  @Override
  public JsonElement serialize(Collection<?> src, Type typeOfSrc,
    JsonSerializationContext context) {
   if (src == null || src.isEmpty())
    return null;

   JsonArray array = new JsonArray();

   for (Object child : src) {
    JsonElement element = context.serialize(child);
    array.add(element);
   }

   return array;
  }
 }
Step 2: Instantiate gson using CollectionAdapter.
Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(Collection.class, new CollectionAdapter()).create();
Following is the complete working application.
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 Employee() {
  super();
 }

 public Employee(int id, String firstName, String lastName) {
  this.id = id;
  this.firstName = firstName;
  this.lastName = lastName;
 }

 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.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class Main {

 static class CollectionAdapter implements JsonSerializer<Collection<?>> {
  @Override
  public JsonElement serialize(Collection<?> src, Type typeOfSrc,
    JsonSerializationContext context) {
   if (src == null || src.isEmpty())
    return null;

   JsonArray array = new JsonArray();

   for (Object child : src) {
    JsonElement element = context.serialize(child);
    array.add(element);
   }

   return array;
  }
 }

 public static void main(String args[]) {
  Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(
    Collection.class, new CollectionAdapter()).create();

  Employee emp1 = new Employee(1, "Hari Krishna", "Gurram");
  Employee emp2 = new Employee(2, "Sandeep", null);

  emp1.getHobbies().add("Trekking");
  emp1.getHobbies().add("Blogging");

  List<Employee> emps = new ArrayList<>();
  emps.add(emp1);
  emps.add(emp2);

  String json = gson.toJson(emps);
  System.out.println(json);

 }
}


Output

[{"id":1,"firstName":"Hari Krishna","lastName":"Gurram","hobbies":["Trekking","Blogging"]},{"id":2,"firstName":"Sandeep"}]




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment