public interface ExclusionStrategy
shouldSkipClass(Class)
method returns true then that class or field type
will not be part of the JSON output. For deserialization, if shouldSkipClass(Class)
returns true, then it will not be set as part of the Java object structure.
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
the GsonBuilder
is required. The following is an example of how you can use the
GsonBuilder
to configure Gson to use one of the above sample:
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 the
GsonBuilder.addDeserializationExclusionStrategy(ExclusionStrategy)
method.
For example:
ExclusionStrategy excludeStrings = new UserDefinedExclusionStrategy(String.class); Gson gson = new GsonBuilder() .addDeserializationExclusionStrategy(excludeStrings) .create();
Modifier and Type | Method and Description |
---|---|
boolean |
shouldSkipClass(java.lang.Class<?> clazz) |
boolean |
shouldSkipField(FieldAttributes f) |
boolean shouldSkipField(FieldAttributes f)
f
- the field object that is under testboolean shouldSkipClass(java.lang.Class<?> clazz)
clazz
- the class object that is under test"Copyright © 2010 - 2020 Adobe Systems Incorporated. All Rights Reserved"