-
public interface ExclusionStrategy
A strategy (or policy) definition that is used to decide whether or not a field or class should be serialized or deserialized as part of the JSON output/input.The following are a few examples that shows how you can use this exclusion mechanism.
Exclude fields and objects based on a particular class type:
private static class SpecificClassExclusionStrategy implements ExclusionStrategy { private final Class<?> excludedThisClass; public SpecificClassExclusionStrategy(Class<?> excludedThisClass) { this.excludedThisClass = excludedThisClass; } public boolean shouldSkipClass(Class<?> clazz) { return excludedThisClass.equals(clazz); } public boolean shouldSkipField(FieldAttributes f) { return excludedThisClass.equals(f.getDeclaredClass()); } }
Excludes fields and objects based on a particular annotation:
public @interface FooAnnotation { // some implementation here } // Excludes any field (or class) that is tagged with an "@FooAnnotation" private static class FooAnnotationExclusionStrategy implements ExclusionStrategy { public boolean shouldSkipClass(Class<?> clazz) { return clazz.getAnnotation(FooAnnotation.class) != null; } public boolean shouldSkipField(FieldAttributes f) { return f.getAnnotation(FooAnnotation.class) != null; } }
Now if you want to configure
Gson
to use a user defined exclusion strategy, then theGsonBuilder
is required. The following is an example of how you can use theGsonBuilder
to configure Gson to use one of the above samples:ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class); Gson gson = new GsonBuilder() .setExclusionStrategies(excludeStrings) .create();
For certain model classes, you may only want to serialize a field, but exclude it for deserialization. To do that, you can write an
ExclusionStrategy
as per normal; however, you would register it with theGsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy)
method. For example:ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class); Gson gson = new GsonBuilder() .addDeserializationExclusionStrategy(excludeStrings) .create();
- Since:
- 1.4
- Author:
- Inderjeet Singh, Joel Leitch
- See Also:
GsonBuilder.setExclusionStrategies(ExclusionStrategy...)
,GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy)
,GsonBuilder.addSerializationExclusionStrategy(ExclusionStrategy)
-
-
Method Summary
All Methods Instance Methods Abstract Methods Modifier and Type Method Description boolean
shouldSkipClass(Class<?> clazz)
boolean
shouldSkipField(FieldAttributes f)
-
-
-
Method Detail
-
shouldSkipField
boolean shouldSkipField(FieldAttributes f)
- Parameters:
f
- the field object that is under test- Returns:
- true if the field should be ignored; otherwise false
-
shouldSkipClass
boolean shouldSkipClass(Class<?> clazz)
- Parameters:
clazz
- the class object that is under test- Returns:
- true if the class should be ignored; otherwise false
-
-