Gson
Serialization
Excluding Fields
Java
Programming Tips

Gson How to exclude specific fields from Serialization without annotations

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Gson, a popular Java library developed by Google, is widely used for converting Java objects into their JSON representation and vice versa. While Gson provides ample flexibility and control over the serialization process, certain scenarios necessitate excluding specific fields from becoming a part of the final JSON output, and sometimes without the use of annotations like @Expose. This requirement can stem from privacy concerns, avoiding circular references, or merely because some fields are irrelevant to the end consumer of your JSON data.

Excluding Fields Without Annotations

Gson offers a mechanism known as custom serialization involving writing a custom ExclusionStrategy. This interface provides a way to apply specific rules which dictate whether a field should be serialized or not. Implementing an exclusion strategy requires overriding two methods: shouldSkipField and shouldSkipClass. The former method allows deciding the fate of individual fields, while the latter can be used to filter out entire classes.

Implementing the Exclusion Strategy

Here’s a step-by-step guide on implementing a custom ExclusionStrategy in Gson:

  1. Define the Exclusion Criteria: Decide on the criteria based on which fields would be excluded. This could be based on modifiers (like transient fields), field names, field types, or custom logic that inspects field values.
  2. Implement the ExclusionStrategy Interface: Create a class that implements ExclusionStrategy and provide implementations for both shouldSkipField and shouldSkipClass. Typically, shouldSkipClass can simply return false if class-level exclusion isn't needed.
  3. Configuring Gson: When building a Gson instance, attach the custom strategy via the GsonBuilder method .setExclusionStrategies(ExclusionStrategy ...).
  4. Serialization/Deserialization: Use the customized Gson instance as usual to serialize or deserialize objects, and the exclusion strategy will filter fields accordingly.

Example: Excluding Specific Field Names

Consider you want to exclude fields named password and socialSecurityNumber for security reasons:

java
1import com.google.gson.ExclusionStrategy;
2import com.google.gson.FieldAttributes;
3import com.google.gson.Gson;
4import com.google.gson.GsonBuilder;
5
6class SensitiveDataExclusionStrategy implements ExclusionStrategy {
7    public boolean shouldSkipField(FieldAttributes f) {
8        return f.getName().equals("password") || f.getName().equals("socialSecurityNumber");
9    }
10
11    public boolean shouldSkipClass(Class<?> clazz) {
12        return false;
13    }
14}
15
16public class Example {
17    private static final Gson GSON = new GsonBuilder()
18        .setExclusionStrategies(new SensitiveDataExclusionStrategy())
19        .create();
20
21    public static void main(String[] args) {
22        User user = new User("JohnDoe", "secretPassword", "123-45-6789");
23        String json = GSON.toJson(user);
24        System.out.println(json); // Output will exclude 'password' and 'socialSecurityNumber'
25    }
26}
27
28class User {
29    private String username;
30    private String password;
31    private String socialSecurityNumber;
32
33    public User(String username, String password, String ssn) {
34        this.username = username;
35        this.password = password;
36        this.socialSecurityNumber = ssn;
37    }
38}

Advantages of Using Exclusion Strategies

Implementing a custom ExclusionStrategy provides several benefits:

  • Flexibility: Customize the serialization process based on dynamic conditions or multi-faceted logic.
  • Decoupling: Keeps the serialization model clean, without annotating domain classes which might be used in different contexts where such exclusions are not needed.
  • Control: Offers the ability to refine the output JSON incrementally by combining multiple strategies or adjusting them at runtime.

Summary Table

Here is a summary of key points concerning using custom exclusion strategies with Gson:

FeatureDescription
Method of ExclusionImplemented via customization of Gson with ExclusionStrategy
Use CasesSecuring sensitive fields, avoiding recursion, selective sharing
FlexibilityHigh to modify output dynamically based on custom conditions
Ease of UseModerate; requires understanding of the underlying model
DependencyOnly on Gson library, no need for additional annotations

Exclusion strategies in Gson offer a powerful tool for shaping JSON output to meet diverse and complex requirements. By understanding and utilizing this feature, developers can exercise granular control over serialization in a clean and efficient manner.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.