How to exclude fields in Gson
Google Gson is a library for serializing and deserializing Java objects to and from JSON. Sometimes, it is necessary to exclude certain fields from the JSON output. Gson provides several ways to achieve this. In this article, we will cover how to exclude fields using various techniques.
1. Set Up Google Gson
Ensure you have Gson in your project’s dependencies. If you are using Maven, add the following to the pom.xml
file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.11.0</version> </dependency>
For Gradle, add this to your build.gradle
:
implementation 'com.google.code.gson:gson:2.11.0'
2. Using the transient
Keyword
The transient
keyword is used to mark a field that should not be serialized. Gson ignores fields marked as transient
.
2.1 Define the User Class
Create a User
class with fields, and mark the fields you want to exclude with the transient
keyword.
public class User { private String name; private transient String password; public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
The above User
class has two fields: name
and password
. The password
field is marked with the transient
keyword, indicating it should be excluded from serialization. The constructor initializes these fields.
2.2 Serialize the User Object
Use Gson to serialize the User
object to JSON.
import com.google.gson.Gson; public class GsonExcludeFieldwithTransient { public static void main(String[] args) { User user = new User("JohnDoe", "secret"); Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); } }
In this example, A Gson
instance is created without any special configuration. The toJson
method serializes the User
object, automatically excluding the password
field because it is marked as transient
. The output JSON string includes only the name
field.
The Program output is:
{"name":"JohnDoe"}
3. Using the @Expose
Annotation
The @Expose
annotation in Gson allows for precise control over which fields are included or excluded during serialization and deserialization. By default, if we use the @Expose
annotation, only fields marked with @Expose
are considered for serialization and deserialization if we use excludeFieldsWithoutExposeAnnotation
in our GsonBuilder
.
3.1 Define the User Class with @Expose
Annotation
Mark the fields we want to include with the @Expose
annotation.
public class User { @Expose private String name; @Expose(serialize = false, deserialize = false) private String password; private int age; public User(String name, String password, int age) { this.name = name; this.password = password; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Code Explanation:
- The
User
class has three fields:name
,password
, andage
. - The
@Expose
annotation marks thename
field for both serialization and deserialization. - The
password
field is marked with@Expose(serialize = false, deserialize = false)
to exclude it from both serialization and deserialization. - The
age
field is not marked with@Expose
and thus will be excluded whenexcludeFieldsWithoutExposeAnnotation
is used.
3.2 Configure Gson with excludeFieldsWithoutExposeAnnotation
Let us set up Gson to exclude fields that are not marked with @Expose
.
public class GsonExcludeFieldExposeMethod { public static void main(String[] args) { User user = new User("JohnDoe", "secret", 30); Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .create(); String json = gson.toJson(user); System.out.println(json); } }
In this example, GsonBuilder
is configured with excludeFieldsWithoutExposeAnnotation
. The excludeFieldsWithoutExposeAnnotation
method ensures that only fields marked with @Expose
are serialized. The toJson
method serializes the User
object, including only the name
field in the JSON output.
The program output is:
{"name":"JohnDoe"}
4. Using ExclusionStrategy
Gson provides the ExclusionStrategy
interface for more fine-grained control over what fields to exclude.
4.1 Define the User Class
As usual, create a simple User
class with the fields to include or exclude during serialization.
public class User { private String name; private String password; public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
4.2 Implement the ExclusionStrategy Interface
Create a class that implements the ExclusionStrategy
interface to define custom rules for excluding fields.
import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; class CustomExclusionStrategy implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getName().equalsIgnoreCase("password"); } @Override public boolean shouldSkipClass(Class clazz) { return false; } }
Explanation:
- The
CustomExclusionStrategy
class implements theExclusionStrategy
interface. - The
shouldSkipField
method checks if the field name ispassword
. If it is, the field is excluded. - The
shouldSkipClass
method can be used to exclude entire classes but returnsfalse
here, meaning no class is excluded.
4.3 Serialize the User Object
Use GsonBuilder
to apply the custom exclusion strategy when serializing the User
object.
public class ExclusionStrategyExample { public static void main(String[] args) { User user = new User("JohnDoe", "secret"); Gson gson = new GsonBuilder() .setExclusionStrategies(new CustomExclusionStrategy()) .create(); String json = gson.toJson(user); System.out.println(json); } }
In the above code, GsonBuilder
is used to configure Gson with the custom exclusion strategy. The toJson
method serializes the User
object, excluding the password
field as defined in CustomExclusionStrategy
.
The program output is:
{"name":"JohnDoe"}
5. Using ExclusionStrategy
and Custom Annotation
For more flexibility, we can use a custom annotation along with ExclusionStrategy
.
5.1 Define the Custom Annotation
Create a custom Java annotation type to mark fields that should be excluded.
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Exclude { }
In the above code:
@Retention(RetentionPolicy.RUNTIME)
specifies that the annotation is available at runtime.@Target(ElementType.FIELD)
indicates that the annotation can be applied to fields.
5.2 Define the User Class with Custom Annotation
Add the custom annotation to the fields we want to exclude.
public class User { private String name; @Exclude private String password; public User(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
The User
class is similar to before but with the @Exclude
annotation on the password
field. The @Exclude
annotation marks the password
field to be excluded.
5.3 Implement the AnnotationExclusionStrategy Class
Create a class that implements ExclusionStrategy
and checks for the custom annotation.
class AnnotationExclusionStrategy implements ExclusionStrategy { @Override public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(Exclude.class) != null; } @Override public boolean shouldSkipClass(Class clazz) { return false; } }
Code Explanation:
- The
AnnotationExclusionStrategy
class implements theExclusionStrategy
interface. - The
shouldSkipField
method checks if the field has the@Exclude
annotation and excludes it if present. - The
shouldSkipClass
method returnsfalse
, meaning no class is excluded.
5.4 Serialize the User Object
Now, use GsonBuilder
to apply the annotation-based exclusion strategy when serializing the User
object.
public class AnnotationExclusionStrategyExample { public static void main(String[] args) { User user = new User("JohnDoe", "secret"); Gson gson = new GsonBuilder() .setExclusionStrategies(new AnnotationExclusionStrategy()) .create(); String json = gson.toJson(user); System.out.println(json); } }
In this code example, GsonBuilder
is configured with the AnnotationExclusionStrategy
. The toJson
method serializes the User
object, excluding the password
field based on the @Exclude
annotation.
Program output:
{"name":"JohnDoe"}
6. Conclusion
In this article, we explored various methods to exclude fields from serialization and deserialization in Gson. We started by setting up Gson and then delved into different techniques:
- Using the
transient
Keyword: A simple approach to mark fields as transient to exclude them from serialization. - Using the
@Expose
Annotation: A straightforward way to explicitly specify which fields should be included or excluded during serialization and deserialization. - Using
ExclusionStrategy
: A method to define custom rules for excluding fields by implementing theExclusionStrategy
interface. - Combining
ExclusionStrategy
with Custom Annotations: This method provides greater control by using custom annotations to mark fields for exclusion and implementing an exclusion strategy to handle these annotations.
7. Download the Source Code
This was an article on how to exclude fields in Gson.
You can download the full source code of this example here: How to exclude fields in Gson