Exclusionstrategy
One of the ways to prevent an attribute from being serialized is by implementing a ExclusionStrategy
, where through the rewriting of the method shouldSkipField()
we will inform whether or not we want an attribute of a class being serialized together, and the method shouldSkipClass()
, 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, enough in creating our instance of Gson through the GsonBuilder
invoke the method addSerializationExclusionStrategy()
:
Gson gson = new GsonBuilder().addSerializationExclusionStrategy(new MeuGsonExclusionStrategy()).create();
Note that there is also the method addDeserializationExclusionStrategy()
, that possesses the same object but for the process of deserialization.
excludeFieldsWithModifiers
A second method to prevent an attribute from being serialized or deserialized is the excludeFieldsWithModifiers()
that expects a constant of java.lang.reflect.Modifier
. This method informs which fields we want to prevent by informing your modifiers. For example, if it is not desired that all the 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 for this function is the excludeFieldsWithoutExposeAnnotation()
, which prevents all attributes that do not have the annotation @Exposed
be serialized or deserialized. That is, all fields that we want to be serialized or deserialized should be annotated with @Exposed
. Follow the example of use below:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();