melchoir55
melchoir55

Reputation: 7276

gson exclusion strategy apply only to fields of target object

I want to prevent Gson from serializing fields of a specific type. For this, I have created an exclusion strategy. The exclusion strategy does successfully recognize when the class in question is being processed and it does successfully exclude it. Unfortunately, it prevents me from serializing objects of that class even when they are the root. By that I mean they are the argument passed to the gson.toJson() method.

To be more clear, I have a class of type Person with class fields that themselves involve the Person type. I do not want to serialize class fields of the type Person.

public class Person{
   private Person child;
   private String name;
}

So, in the above example, I want a json object containing the name field but not the child field. I want the solution to be sensitive the the type of the field, not the field name.

Upvotes: 0

Views: 4959

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280148

An ExclusionStrategy defines two methods, one to exclude types and one to exclude fields. Just use the field method to skip any fields of type Person.

class PersonExcluder implements ExclusionStrategy {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getDeclaredType().equals(Person.class);
    }

    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        return false;
    }
}

then use register it

Gson gson = new GsonBuilder().setExclusionStrategies(new PersonExcluder()).create();

Upvotes: 2

Related Questions