How to exclude fields from JSON while parsing by GSON/GsonBuilder?

In below previous exaxmples. We discussed about to convert JAVA object to/ from to JSON and pretty formatting and null serailization of fields for JSON conversion. Now here we discussed about how to exclude fields/object while converting to JSON.

How to convert Java object to / from JSON by (GSON)

How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder)

GSON provide two ways to exclude fields from JSON by GsonBuilder:

  • @Expose Annotation
  • Custom Annotation

@Expose Annotation

By using the @Expose annotations and then using the excludeFieldsWithoutExposeAnnotation() method on the GsonBuilder will ignore all fields except the ones that have been exposed using the @Expose annotation.

Custom Annotation

By defining a custom annotation and ignoring fields that are annotated with exclusion class by extending ExclusionStrategy interface implementing that by using below GsonBuilder methods can ingnore/exclude fields from JSON.

Boolean shouldSkipField(FieldAttributes f);

public boolean shouldSkipClass(Class clazz);


  • JAVA 8
  • Maven 3
  • GSON Jar as below.

GSON Dependency:


In below example fields middleName,educationDetail and experienceDetail will not serialize because not having @Expose annotation on it and field country will also not serialize because of having @Country annotation. Here you will see how to unsearilize all these

package gsonexamples;


import model.AlbumImages;
import model.Albums;
import model.Country;
import model.Dataset;
import model.Employee;
import util.CustomExclusionStrategy;

class GsonConvertJavaObjectToJSONExclusion {

	public static void main(String[] args) {
		Employee employee= getJavaObject();
		//CustomExclusionStrategy that will exclude the Country field.
// We also allow only those fields that have been exposed using the @Expose

				Gson gson = new GsonBuilder()
				.setExclusionStrategies(new CustomExclusionStrategy(Country.class))



	public static  Employee getJavaObject()
		Employee employee=new Employee("C123","Saurabh" ,"Kumar","Gupta","Tech Lead",50000,"Alpharetta,GA","Dallas, TX","1231231230",null,null);
		return employee;


package util;


import model.Country;
import model.Dataset;

 * This class use 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 type policy can be applied to any *  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
	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.
	public boolean shouldSkipClass(Class<?> clazz) {
		if (clazz.equals(classToExclude))
			return true;
		return false;

package model;

import java.util.List;
import java.util.Set;


public class Employee {
	private String employeeId;
	private String firstName;
	private String middleName;
	private String lastName;
	private String designation;
	private int salary;
	private String permanentAddress;
	private String mailingAddress;
	private String country;
	private String mobile;
	private Set<Education> educationDetail;
	private List<Experience> expericeDetail;

	public String toString() {
		return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", middleName=" + middleName
				+ ", lastName=" + lastName + ", designation=" + designation + ", salary=" + salary
				+ ", permanentAddress=" + permanentAddress + ", mailingAddress=" + mailingAddress + ", mobile=" + mobile
				+ ", educationDetail=" + educationDetail + ", expericeDetail=" + expericeDetail + "]";

	public Employee(String employeeId, String firstName, String middleName, String lastName, String designation,
			int salary, String permanentAddress, String mailingAddress, String mobile, Set<Education> educationDetail,
			List<Experience> expericeDetail) {
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.designation = designation;
		this.salary = salary;
		this.permanentAddress = permanentAddress;
		this.mailingAddress = mailingAddress; = mobile;
		this.educationDetail = educationDetail;
		this.expericeDetail = expericeDetail;
//Getter and setter of fields

package model;

public class Education {
private String schoolOrCollegeName;
private String standard;
private String stream;
private double percentage;

public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard; = stream;
	this.percentage = percentage;
package model;

import java.util.Date;

public class Experience {
private String companyName;
private String designation;
private Date startDate;
private Date endDate;
private double salary;
public Experience(String companyName, String designation, Date startDate, Date endDate, double salary) {
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
//getter and setter


  "employeeId": "C123",
  "firstName": "Saurabh",
  "lastName": "Gupta",
  "designation": "Tech Lead",
  "permanentAddress": "Alpharetta,GA",
  "mobile": "1231231230"

Here in above JSON output for Employee class fields middleName, educationDetail and experienceDetail not printed because @Expose annotation was not given on that and by using CustomExlusionStartegy skiping serialization for fields country because it’s having @Country annotation as we remove in class for serialization CustomExclusionStrategy for @Country annotation.

Now in next example will discuss about.

How to parse JSON data token by token by using GSON/JsonToken/JsonReader?

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in GSON, JSON, Uncategorized and tagged , , , , , , , . Bookmark the permalink.

One Response to How to exclude fields from JSON while parsing by GSON/GsonBuilder?

  1. Pingback: How to do JSON pretty formatting and Null Serialization (GSON/GsonBuilder) | Facing Issues On IT

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s