Java Google Json (Gson) Exclusion Strategy

In this tutorial we look at how to selectively include fields from a java object to a json string. By default, Gson tries to map all fields in the java object to the corresponding property in json. However, in certain cases we may want to control that. There are a few ways to do this. It is also possible to excluse fields from third party packages where we have no access to the source code. The different ways to exclude fields are :

  1. By defining a custom annotation and ignoring fields that are annotated with that.
  2. By Defining a custom exclusion class by extending the ExclusionStrategy interface and implementing the public boolean shouldSkipField(FieldAttributes f); and public boolean shouldSkipClass(Class clazz); methods
  3. By using the @Expose annotations and then using the excludeFieldsWithoutExposeAnnotation() method on the GsonBuilder. This will ignore all fields except the ones that have been exposed using the @Expose annotation.

The example below demonstrates all three

package com.studytrails.json.gson;

import java.awt.Color;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class ExclusionExample {
	public static void main(String[] args) {
		// We create an instance of type CAT.
		Cat cat = new Cat();
		cat.setName("Cat");
		cat.setAge(1);
		cat.setColor(Color.BLACK);
		cat.setCountry("US");
		// we allow serializing null. therefore although the fields lazy is
		// null, it will be serialized. We add a CustomExclusionStrategy that
		// will exclude the Color class. We also allow only those fields that
		// have been exposed using the @Expore annotation
		Gson gson = new GsonBuilder().serializeNulls().setExclusionStrategies(new CustomExclusionStrategy(Color.class))
				.excludeFieldsWithoutExposeAnnotation().create();
		System.out.println(gson.toJson(cat));
		// prints {"name":"Cat","lazy":null}

	}
}

The Cat class

package com.studytrails.json.gson;

import java.awt.Color;

import com.google.gson.annotations.Expose;

public class Cat {
	@Expose
	private String name;
	private int age;
	private Color color;
	@Expose
	@Country
	private String country;
	@Expose
	private Boolean lazy = null;

	public void setAge(int age) {
		this.age = age;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setColor(Color color) {
		this.color = color;
	}

	public int getAge() {
		return age;
	}

	public String getName() {
		return name;
	}

	public Color getColor() {
		return color;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getCountry() {
		return country;
	}

	public void setLazy(Boolean lazy) {
		this.lazy = lazy;
	}

	public Boolean getLazy() {
		return lazy;
	}
}

The Exclusion Strategy

package com.studytrails.json.gson;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

/**
 * This class defines custom exclusion policy. We want to ignore all fields that
 * have been annotated with the Country annotation. Note that we can also ignore
 * fields based on name or type. This same policy can be applied to any class.
 * In this example we apply to the CAT class, but it is not limited to the cat
 * class.
 * 
 */
public class CustomExclusionStrategy implements ExclusionStrategy {

	private Class classToExclude;

	public CustomExclusionStrategy(Class classToExclude) {
		this.classToExclude = classToExclude;
	}

	// This method is called for all fields. if the method returns false the
	// field is excluded from serialization
	@Override
	public boolean shouldSkipField(FieldAttributes f) {
		if (f.getAnnotation(Country.class) == null)
			return false;

		return true;
	}

	// This method is called for all classes. If the method returns false the
	// class is excluded.
	@Override
	public boolean shouldSkipClass(Class<?> clazz) {
		if (clazz.equals(classToExclude))
			return true;
		return false;
	}

}

Leave a Comment