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.
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:
- 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.
- Implement the ExclusionStrategy Interface: Create a class that implements
ExclusionStrategyand provide implementations for bothshouldSkipFieldandshouldSkipClass. Typically,shouldSkipClasscan simply returnfalseif class-level exclusion isn't needed. - Configuring Gson: When building a
Gsoninstance, attach the custom strategy via theGsonBuildermethod.setExclusionStrategies(ExclusionStrategy ...). - 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:
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:
| Feature | Description |
| Method of Exclusion | Implemented via customization of Gson with ExclusionStrategy |
| Use Cases | Securing sensitive fields, avoiding recursion, selective sharing |
| Flexibility | High to modify output dynamically based on custom conditions |
| Ease of Use | Moderate; requires understanding of the underlying model |
| Dependency | Only 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
- GSON throwing Expected BEGIN_OBJECT but was BEGIN_ARRAY?
- GSON throwing Expected BEGIN_OBJECT but was BEGIN_ARRAY?
- H2 database console spring boot Load denied by X-Frame-Options
- Hadoop NoClassDefFoundError when adding external Jar
- Handling exceptions from Java ExecutorService tasks
- Handling exceptions from Java ExecutorService tasks
- Handling InterruptedException in Java
- Handling InterruptedException in Java

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.