Preventing an attribute from being serialized or deserialized

Asked

Viewed 151 times

1

I am using Gson on a web service and need to prevent some attributes from being serialized and others that are prevented from being deserialized. One of the reasons to prevent serialization is due to the loop that is entered when going to serialize 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 in one side of the bi-directional relationship to prevent mistakes?

1 answer

1


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();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.