Excluding Fields From Serialization


Gson supports numerous mechanisms for excluding top-level classes, fields and field types, lets view the manner of exclusion provided by Gson

  • Transient Fields
  • The @Expose Annotation
  • GsonBuilder.setExclusionStrategies()

>_Transient Fields

If we make a field in a Java class as transient then GSON will ignore for both serialization and deserialization.

Check this example where Player class 'gender' field marked as transient.

/**

							
							 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;

import java.util.LinkedList;
import java.util.List;

public class Player {
	public String name;
	public transient String gender;
	public int age;
	public List<String> gamesplayed = new LinkedList<>();
}
/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;

import com.google.gson.Gson;

public class ToJsonParsingExample {
	public static void main(String args[]) {
		Player obj = new Player();
		String jsonString = null;
		obj.age = 29;
		obj.name = "Alex";
		obj.gender = "Male";
		Gson gson = new Gson();
		jsonString = gson.toJson(obj);
		System.out.println(jsonString);
	}
}
Output Of ToJsonParsingExample :-
{"name":"Alex","age":29,"gamesplayed":[]}

>_The @Expose Annotation

The GSON @Expose annotation (com.google.gson.annotations.Expose) can be used to mark a field to be exposed or not (included or not) for serialized or deserialized.

The @Expose annotation can take two parameters. Each parameter is a boolean which can take either the value true or false. Here are some GSON @Expose annotation examples.

@Expose(serialize = true);
@Expose(serialize = false);
@Expose(deserialize = true);
@Expose(deserialize = false);
@Expose(serialize = true , deserialize = false);
@Expose(serialize = false, deserialize = true);

The @Expose annotation's serialize parameter specifies if the field annotated with the @Expose annotation should be included when the owning object is serialized.

The deserialize parameter specifies whether that field should be read when the owning object is deserialized.


Here is an example class using the GSON @Expose annotation:

public class Player {
	@Expose(serialize = true, deserialize = true)
	public String name;
	@Expose(serialize = false, deserialize = false)
	public String gender;
	@Expose(serialize = true, deserialize = true)
	public int age;
	public List<String> gamesplayed = new LinkedList<>();
}

@Expose annotation placed above the fields, telling whether the given field should be included when serialized or deserialized.
In order to get GSON to react to the @Expose annotations you must create a Gson instance using the GsonBuilder class.
Let's See How to create it


GsonBuilder builder = new GsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();

!! NOTE:-

This configuration makes GSON ignore all fields that do not have an @Expose annotation. To have a field included in serialization or deserialization it must have an @Expose annotation above it. check this program for better understanding

/**
 * @author TutorialToUs.com
 */
package com.tutorialtous.gson;

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

public class ToJsonParsingExample {
	public static void main(String args[]) {
		Player obj = new Player();
		String jsonString = null;
		obj.age = 29;
		obj.name = "Alex";
		obj.gender = "Male";
		GsonBuilder builder = new GsonBuilder();
		builder.excludeFieldsWithoutExposeAnnotation();
		Gson gson =builder.create();
		jsonString = gson.toJson(obj);
		System.out.println(jsonString);
	}
}

>_GsonBuilder.setExclusionStrategies()

Another way to exclude a field from serialization or deserialization in GSON is to set an ExclusionStrategy on a GsonBuilder, and use that GsonBuilder to build the Gson object with.

ExclusionStrategy is an interface, so we will have to create a class that implements the ExclusionStrategy interface. Here is an example that implements the ExclusionStrategy interface with an anonymous class:


ExclusionStrategy exclusionStrategy = new ExclusionStrategy() {
    public boolean shouldSkipField(FieldAttributes fieldAttributes) {
        if("gender".equals(fieldAttributes.getName())){
            return true;
        }
        return false;
    }

    public boolean shouldSkipClass(Class aClass) {
        return false;
    }
};

To use the ExclusionStrategy implementation create a GsonBuilder and set the ExclusionStrategy on it using the setExclusionStrategies() method, like this

GsonBuilder builder = new GsonBuilder();
builder.setExclusionStrategies(exclusionStrategy);
Gson gson = builder.create();

The exclusionStrategy variable has to point to an implementation of the ExclusionStrategy interface.