Gson – Exclude or ignore fields

Gson allows us to exclude or ignore the fields from Java classes which we want not to be included in serialization and deserialization. Gson supports many inbuilt mechanisms for excluding top-level classes, fields and field types.

1. Gson @Expose annotation

@Expose marks certain fields of the objects to be excluded, by default, for consideration for serialization and deserialization to JSON. It means that Gson will exclude all fields in a class that are not marked with @Expose annotation.

The @Expose annotation is useful in a style of programming where you want to explicitly specify all fields that should get considered for serialization or deserialization.

1.1. How to use @Expose

@Expose is optional and offers two configuration parameters :

  • serialize – If true, the field marked with this annotation is written out in the JSON while serializing.
  • deserialize – If true, the field marked with this annotation is deserialized from the JSON.
@Expose(serialize = false) 
private String lastName;

@Expose (serialize = false, deserialize = false) 
private String emailAddress;

1.2. Creating Gson instance

If we created Gson with new Gson(), and execute the toJson() and fromJson() methods then @Expose will not have any effect on serialization and deserialization.

To use this annotation, we must create Gson instance by using GsonBuilder class and it’s excludeFieldsWithoutExposeAnnotation() method.

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

2. Exclude fields with modifiers

2.1. transient fields

By default, Gson would exclude a field from serialization and deserialization – both, if we simply mark the field as transient. Remember that it is not capable of blocking one way transformation. It blocks both.

transient will have the same effect as @Expose (serialize = false, deserialize = false).

@Expose(serialize = false) 
private String lastName;

private transient String emailAddress;

2.2. Other modifiers

By using excludeFieldsWithModifiers() method of GsonBuilder, we can exclude fields which have some common modifier.

For example, we want to exclude all static members of a class, the we can create the Gson object like this:

Gson gson = new GsonBuilder()
		.excludeFieldsWithModifiers(Modifier.STATIC)
		.create();

We can use any number of the Modifier constants to “excludeFieldsWithModifiers” method. For example:

Gson gson = new GsonBuilder()
		.excludeFieldsWithModifiers(Modifier.STATIC, 
							Modifier.TRANSIENT, 
							Modifier.VOLATILE)
		.create();

3. Exclusion Strategies

If any of above given technique is not working for us, then we can create our own strategy. ExclusionStrategy is used to decide whether or not a field or top-level class should be serialized or deserialized as part of the JSON output/input.

  • For serialization, if the shouldSkipClass(Class) or shouldSkipField(fieldAttributes) methods return true then that class or field type will not be part of the JSON output.
  • For deserialization, if shouldSkipClass(Class) or shouldSkipField(fieldAttributes) methods return true, then it will not be set as part of the Java object structure.

For example, below ExclusionStrategy definition will exclude all fields annotated with @Hidden annotation.

//public @interface Hidden {
	// some implementation here
//}

// Excludes any field (or class) that is tagged with an "@Hidden"
public class HiddenAnnotationExclusionStrategy implements ExclusionStrategy 
{
	public boolean shouldSkipClass(Class<?> clazz) {
	 	return clazz.getAnnotation(Hidden.class) != null;
	}

	public boolean shouldSkipField(FieldAttributes f) {
	 	return f.getAnnotation(Hidden.class) != null;
	}
}

To use this exclusion startegy, set it in GsonBuilder object.

GsonBuilder builder = new GsonBuilder();
builder.setExclusionStrategies( new HiddenAnnotationExclusionStrategy() );

Gson gson = builder.create();

Still if none of the above mechanisms satisfy our needs then we can always use custom serializers and deserializers.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.