Skip to content

Gson – Exclude or Ignore Specific Fields

Gson – exclude or ignore specific fields example shows how to exclude fields or ignore fields while serialization or deserialization using the Gson library in Java.

How to exclude or ignore fields from serialization in Java Gson?

There are several ways using which we can exclude fields while serializing to the JSON.

1. Using the transient

The easiest way to exclude specific fields from serialization is to mark them as transient fields. In the below given example, I’ve marked the age field as transient, so it will not be included in the JSON when the object is serialized.

Output

As we can see from the output, the age field is ignored and excluded from the JSON.

Important Note: While this approach is the easiest, it ignores the field marked as transient from being serialized and deserialized. If you want to ignore a specific field only during serialization or deserialization, this approach will not work.

2. Using the Expose annotation

We can also mark all the fields with the Expose annotation that we want to serialize or deserialize. We also need to create a Gson object using the GsonBuilder along with the excludeFieldsWithoutExposeAnnotation method call as given below.

Output

In this approach, we need to mark all the fields with the Expose annotation that we want to serialize/deserialize. If we have hundreds of fields, it might be cumbersome to mark all of them with the annotation.

3. Using the exclusion strategy

We can set the exclusion strategy while creating the Gson object using the GsonBuilder by using the setExclusionStrategies method. We need to implement the ExclusionStrategy interface in our custom strategy class and pass an object of it to the setExclusionStrategies method as given below.

Output

As we can see from the output, the “name” field is ignored/excluded from the generated JSON from both the classes, Employee, and Company.

If we want to ignore just the company name, we can make the below-given changes to the strategy.

Output

Now, only the “name” field of the Company class is ignored.

The ExclusionStretegies apply to both, serialization and deserialization. If we want to apply the strategy to either one of them or if we want to apply a different strategy for serialization and deserialization, we can use the addSerializationExclusionStrategy and addDeserializationExclusionStrategy methods instead of the setExclusionStrategies method while creating a Gson object.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.