Gson provides customization to exclude certain fields during serialization. This tutorial covers how to skip fields from serialization using custom Exclusion Strategy. Exclusion Strategy supports 2 ways to exclude fields.

  • Exclude fields using custom Annotation
  • Exclude fields of specific Data Type

1. Exclude fields using custom annotation

Let’s say we have requirement to exclude dateOfBirth from JSON Object format. Instead of mentioning all the other fields with @Expose annotation provided by Gson, we could exclude specific fields using custom annotation.

Steps:

  • Define Custom Annotation
  • Define Exclusion Strategy around custom annotation
  • Annotate fields to be skipped from serialization/de-serialization
  • Configure the Exclusion Strategy and Run Application

1.1 Define Custom Annotation. Ex @Exclude

Let’s define custom annotation to use on the fields we want to skip.

Exclude.java
package com.codesimplify.gson.excludeexamples;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Exclude {

}

1.2 Define Exclusion Strategy around custom annotation

Below custom exclusion strategy explain how to exclude fields declared with specific annotation. Since our strategy is to skip fields marked with specific annotation, we need to implement shouldSkipField() method.

MyExclusionStratagy .java
package com.codesimplify.gson.excludeexamples;

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

public class MyExclusionStratagy implements ExclusionStrategy {

	public boolean shouldSkipField(FieldAttributes f) {
		if(f.getAnnotation(Exclude.class)!=null){
			return true;
		}
		return false;
	}

	public boolean shouldSkipClass(Class clazz) {
		// TODO Auto-generated method stub
		return false;
	}

}

1.3 Annotate fields to be skipped from serialization/de-serialization

We have defined annotation and custom Exclusion Strategy. Now, we will use the @Exclude annotation on fields to be skipped from serialization

Person.java
package com.codesimplify.gson.excludeexamples;

import java.util.Date;

public class Person {
	
	public Person(String firstName, String lastName, int age,Date dateOfBirth) {
		super();
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.dateOfBirth = dateOfBirth;		
	}
	String firstName;
	String lastName;	
	int age;	
	@Exclude
	Date dateOfBirth;
}

1.4 Configure the Exclusion Strategy and Run Application

In this step, we will configure the custom Exclusion Strategy defined around @Exclude annotation. If we observe the output, we can see dateOfBirth is skipped from serialization.

package com.codesimplify.gson.excludeexamples;

import java.sql.Date;
import java.time.LocalDate;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")
        		.setExclusionStrategies(new MyExclusionStratagy())
        		.create();
        Person pers=new Person("Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
             
    }		
}

Output:

JAVA to JSON:{
“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30
}

2. Exclude fields of specific Data Type

If the requirement is to skip certain Data Types from serialization and not to modify existing java beans, we can see how this will be addressed with below example.

Steps:

  • Define java Beans
  • Define Custom Exclusion Strategy to exclude specific data types.
  • Configure Custom Exclusion Strategy and Run Application.

2.1 Define java Beans

In most of the applications, we could see certain application specific data types ( For instance Id type we see below ) which we don’t want to serialize as part of JSON Object format.

Id.java
package com.codesimplify.gson.excludetype;

public class Id {
	
	private final int value;
	private Id(int value){
		this.value=value;
	}
	public static Id valueOf(int value){
		return new Id(value);
	}
	public String toString(){
		return String.valueOf(value);
	}

}
Person.java
package com.codesimplify.gson.excludetype;

import java.util.Date;

public class Person {
	
	public Person(Id id,String firstName, String lastName, int age,Date dateOfBirth) {
		super();
		this.id=id;
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.dateOfBirth = dateOfBirth;		
	}
	Id id;
	String firstName;
	String lastName;	
	int age;	
	Date dateOfBirth;
}

2.2 Define Custom Exclusion Strategy to exclude specific data types

Below ExclusionStrategy class is implemented to exclude Id Type. shouldSkipClass() method is implemented to skip all the fields of Id type.

MyExclusionStratagy.java
package com.codesimplify.gson.excludetype;

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

public class MyExclusionStratagy implements ExclusionStrategy {

	public boolean shouldSkipField(FieldAttributes f) {
		
		return false;
	}

	public boolean shouldSkipClass(Class clazz) {
		if(clazz.getCanonicalName().equals("com.codesimplify.gson.excludetype.Id")){
			return true;
		}
		return false;
	}

}

2.3 Configure Custom Exclusion Strategy and Run Application

MyExclusionStrategy is added to Gson configuration though setExclusionStrategies(). If we observe the JSON Output, fields declared with Id Type are skipped during serialization.

App.java
package com.codesimplify.gson.excludetype;

import java.sql.Date;
import java.time.LocalDate;


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

public class App 
{
	public static void main( String[] args )
    {        
        Gson gson=new GsonBuilder()
        		.setPrettyPrinting()
        		.setDateFormat("yyyy-MM-dd")
        		.setExclusionStrategies(new MyExclusionStratagy())
        		.create();
        Person pers=new Person(Id.valueOf(10),"Venkat","Gutta",30,Date.valueOf(LocalDate.of(1986, 1, 1)));
        System.out.println("JAVA to JSON:"+gson.toJson(pers));
             
    }		
}

Output:
Without Exclusion Strategy: Id Type is serialized.

JAVA to JSON:{
“id”: {
“value”: 10
},

“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“dateOfBirth”: “1986-01-01”
}

With Exclusion Strategy:

JAVA to JSON:{
“firstName”: “Venkat”,
“lastName”: “Gutta”,
“age”: 30,
“dateOfBirth”: “1986-01-01”
}

Gson : Exclude fields from Serialization using Exclusion Strategy
Tagged on:             

One thought on “Gson : Exclude fields from Serialization using Exclusion Strategy

Leave a Reply

Your email address will not be published. Required fields are marked *