Gson ExclusionStrategy Example

What if you want to exclude some fields from Serialization and Deserialization? Gson provides several ways to handle this scenario.

1) Using @Expose annotation

GsonBuilder’s excludeFieldsWithoutExposeAnnotation() method is a handy way to exclude certain fields from being serialized/deserialized. Just annotate the fields you want to be serialized/deserialzed with @Expose annotation. Don’t annotate the fields which you want to exclude from serialization/deserialization.

In below class, Field ‘cost’ will be excluded from Serialization/Deserializaion. Also notice the transient on the field ‘power’. Any field which is marked with ‘transient’ will not be serialized/deserialized no matter if it is annotated or not.

package com.websystique.json.gson;

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

import com.google.gson.annotations.Expose;

public class Car {

	@Expose
	private String name;
	
	@Expose
	private int model;
	
	private double cost;
	
	private transient String power;		//transient will never be (de)serialized
	
	@Expose
	private List<String> colors = new ArrayList<String>();

	public String getName() {
		return name;
	}

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

	public int getModel() {
		return model;
	}

	public void setModel(int model) {
		this.model = model;
	}

	public double getCost() {
		return cost;
	}

	public void setCost(double cost) {
		this.cost = cost;
	}

	public List<String> getColors() {
		return colors;
	}

	public void setColors(List<String> colors) {
		this.colors = colors;
	}

	public String getPower() {
		return power;
	}

	public void setPower(String power) {
		this.power = power;
	}

	@Override
	public String toString() {
		return "Car [name=" + name + ", model=" + model + ", cost=" + cost
				+ ", power=" + power + ", colors=" + colors + "]";
	}
	
	
}

Following is the Main

package com.websystique.json.gson;

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

public class GsonExclusionStrategyExample {

	public static void main(String args[]){
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		
		Car car = new Car();
		car.setName("AUDI");
		car.setModel(2014);
		car.setCost(45000);
		car.setPower("120HP");
		car.getColors().add("GREY");
		car.getColors().add("BLACK");
		car.getColors().add("WHITE");

		/*Serialize */
		String jsonString = gson.toJson(car); 
		System.out.println("jsonString : "+ jsonString);
	
		
		
		/*Deserialize*/
		String inputJson  = "{\"name\":\"AUDI\",\"model\":2014, \"cost\":30000,\"power\":\"300HP\",\"colors\":[\"GRAY\",\"BLACK\",\"WHITE\"]}";
		car = gson.fromJson(inputJson, Car.class);
		System.out.println("Car : "+ car);

	}
}

Run it. You get following output:

jsonString : {"name":"AUDI","model":2014,"colors":["GREY","BLACK","WHITE"]}
Car : Car [name=AUDI, model=2014, cost=0.0, power=null, colors=[GRAY, BLACK, WHITE]]

Notice that fields ‘cost’ & ‘power’ are missing from serialized json string. Also note that during deserialization too, fields ‘cost’ & ‘power’ are not populated.

2) Implementing ExclusionStrategy

You might have notices that in above example, you have to have access to the class in order to annotate certain fields. What if you don’t have access to source and only know the contract.

In such scenario, we can provide a custom implementation of ExclusionStrategy and register it with GsonBuilder. No need to modify source of model class.

For example, below implementation implements ExclusionStrategy. It exhibits the way we can skip certain fields. Here we are excluding a field with name ‘cost’ but you are free to apply your own criteria while implementing ExclusionStrategy interface.

package com.websystique.json.gson;

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

public class CustomExclusionStrategy implements ExclusionStrategy {

	public boolean shouldSkipField(FieldAttributes f) {
		return (f.getDeclaringClass() == Plane.class && f.getName().equals("cost"));
	}

	public boolean shouldSkipClass(Class<?> clazz) {
		return false;
	}

}

Now register this implementation with GsonBuilder.

package com.websystique.json.gson;

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

public class GsonCustomExclusionStrategyExample {
	public static void main(String args[]){
		
		Gson gson = new GsonBuilder().setExclusionStrategies(new CustomExclusionStrategy()).create();
		
		Plane plane = new Plane();
		plane.setName("DREAMLINER");
		plane.setModel(2014);
		plane.setCost(245000);
		plane.setPower("120HP");
		plane.getColors().add("GREY");
		plane.getColors().add("BLACK");
		plane.getColors().add("WHITE");

		/*Serialize */
		String jsonString = gson.toJson(plane); 
		System.out.println("jsonString : "+ jsonString);
	
		
		
		/*Deserialize*/
		String inputJson  = "{\"name\":\"JUMBO\",\"model\":2014, \"cost\":230000,\"power\":\"300HP\",\"colors\":[\"GRAY\",\"BLACK\",\"WHITE\"]}";
		plane = gson.fromJson(inputJson, Plane.class);// Convert JSON String to car object
		System.out.println("Plane : "+ plane);

	}
}

Pojo ‘plain’ used above are mentioned below

package com.websystique.json.gson;

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

public class Plane {

	private String name;

	private int model;
	
	private double cost;
	
	private transient String power;		//transient will never be (de)serialized
	
	private List<String> colors = new ArrayList<String>();
	
	public String getName() {
		return name;
	}

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

	public int getModel() {
		return model;
	}

	public void setModel(int model) {
		this.model = model;
	}

	public double getCost() {
		return cost;
	}

	public void setCost(double cost) {
		this.cost = cost;
	}

	public List<String> getColors() {
		return colors;
	}

	public void setColors(List<String> colors) {
		this.colors = colors;
	}

	public String getPower() {
		return power;
	}

	public void setPower(String power) {
		this.power = power;
	}

	@Override
	public String toString() {
		return "Plane [name=" + name + ", model=" + model + ", cost=" + cost
				+ ", power=" + power + ", colors=" + colors + "]";
	}
	

}

Run above Main, you get following output.

jsonString : {"name":"DREAMLINER","model":2014,"colors":["GREY","BLACK","WHITE"]}
Plane : Plane [name=JUMBO, model=2014, cost=0.0, power=null, colors=[GRAY, BLACK, WHITE]]

It’s evident from above output that ‘cost’ field was not serialized & deserialized. In addition, due to transient type, ‘power’ field too was not serialized/deserialized.

That’s it. In the next post we will learn about frequently used Google Gson Json annotations.

References

If you like tutorials on this site, why not take a step further and connect me on Facebook , Google Plus & Twitter as well? I would love to hear your thoughts on these articles, it will help me improve further our learning process.

If you appreciate the effort I have put in this learning site, help me improve the visibility of this site towards global audience by sharing and linking this site from within and beyond your network. You & your friends can always link my site from your site on www.websystique.com, and share the learning.

After all, we are here to learn together, aren’t we?