Preventing an attribute from being serialized or deserialized

1

I'm using Gson in a web service and I need to prevent some attributes from being serialized and others that are prevented from being deserialized. One of the reasons for preventing a serialization is due to the loop that is entered when serializing an object that has a bidirectional relationship with another, thus generating an exception of StackOverFlow . Is there any way to do this or will I have to insert null on one side of the bidirectional relationship to prevent errors?

    
asked by anonymous 11.05.2017 / 15:10

1 answer

1

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();
    
11.05.2017 / 15:11