ExclusionStrategy
One of the ways to prevent an attribute from being serialized is by implementing a
ExclusionStrategy
, where by rewriting the
shouldSkipField()
method we will inform you whether or not we want an attribute of a serialized class to be serialized, and the
shouldSkipClass()
method, where the focus becomes the class, whether or not we want a class to be serialized.
class MeuGsonExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes fieldAttributes) {
return fieldAttributes.getName().equals("meuatributo");
}
@Override
public boolean shouldSkipClass(Class<?> aClass) {
return aClass.getName().equals("com.example.MinhaClasse");
}
}
After that, just create our instance of Gson through GsonBuilder
invoke method addSerializationExclusionStrategy()
:
Gson gson = new GsonBuilder().addSerializationExclusionStrategy(new MeuGsonExclusionStrategy()).create();
Notice that there is also the addDeserializationExclusionStrategy()
method, which has the same object but for the deserialization process.
excludeFieldsWithModifiers
A second method to prevent an attribute from being serialized or deserialized is the excludeFieldsWithModifiers()
that expects as a parameter a java.lang.reflect.Modifier
constant. This method informs which fields we want to prevent by reporting its modifiers. For example, if it is not desired that all final attributes are serialized or deserialized, we do so:
Gson gson = new GsonBuilder().excludeFieldsWithModifiers(java.lang.reflect.Modifier.FINAL).create();
excludeFieldsWithoutExposeAnnotation
A third method to be commented out for this function is excludeFieldsWithoutExposeAnnotation()
, which prevents all attributes that do not have the @Exposed
annotation from being serialized or deserialized. That is, all the fields we want to be serialized or deserialized must be annotated with @Exposed
. Here is the example use below:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();