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);

Pre-Requisite:

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

GSON Dependency:

 <dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
 </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 com.google.gson.Gson;
import com.google.gson.GsonBuilder;

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
//annotation

				Gson gson = new GsonBuilder()
				.setPrettyPrinting()
				.serializeNulls()
				.setExclusionStrategies(new CustomExclusionStrategy(Country.class))
				.excludeFieldsWithoutExposeAnnotation()
				.create();

		System.out.println(gson.toJson(employee));

	}

	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 com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;

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
	//@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;
	}

}
package model;

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

import com.google.gson.annotations.Expose;

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

	@Override
	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) {
		super();
		this.employeeId = employeeId;
		this.firstName = firstName;
		this.middleName = middleName;
		this.lastName = lastName;
		this.designation = designation;
		this.salary = salary;
		this.permanentAddress = permanentAddress;
		this.mailingAddress = mailingAddress;
		this.mobile = 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;

@Override
public String toString() {
	return "Education [schoolOrCollegeName=" + schoolOrCollegeName + ", standard=" + standard + ", stream=" + stream
			+ ", percentage=" + percentage + "]";
}
public Education(String schoolOrCollegeName, String standard, String stream, double percentage) {
	super();
	this.schoolOrCollegeName = schoolOrCollegeName;
	this.standard = standard;
	this.stream = 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) {
	super();
	this.companyName = companyName;
	this.designation = designation;
	this.startDate = startDate;
	this.endDate = endDate;
	this.salary = salary;
}
@Override
public String toString() {
	return "Experience [companyName=" + companyName + ", designation=" + designation + ", startDate=" + startDate
			+ ", endDate=" + endDate + ", salary=" + salary + "]";
}
//getter and setter
}

Output

{
  "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?

Advertisements

One thought on “How to exclude fields from JSON while parsing by GSON/GsonBuilder?”

This site uses Akismet to reduce spam. Learn how your comment data is processed.