svenkapudija
svenkapudija

Reputation: 5166

GSON don't serialize/deserialize extended class

Is there an option (except writing custom serializer/deserializer) in GSON library to NOT serialize/deserialize beyond some level of extended classes.

For example see the following usecase

class FirstClass {
    int firstVariable;
}

class SecondClass extends FirstClass {
    int secondVariable;
}

class ThirdClass extends SecondClass {
    int thirdVariable;
}

And now when using fromJson and toJson I would like to only serialize/deserialize first two classes in hierarchy - ThirdClass and SecondClass. Which means it would ignore whole FirstClass (and firstVariable in it) because that's already at level 3.

Upvotes: 3

Views: 3362

Answers (2)

user17632524
user17632524

Reputation: 1

The below example can help in skipping the certain variable with in the class during serialization

if (fieldAttributes.getDeclaringClass() == Example.class )
                && fieldAttributes.getName().equals("example")) {
            return true;
        }

Upvotes: 0

Jonas Adler
Jonas Adler

Reputation: 913

You cannot generically exclude the TopLevel Class, what you could do is use an ExclusionStrategy:

  private static final Gson GSON = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        return f.getDeclaringClass().equals(FirstClass.class);
    }

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

You can also add a ExclusionStrategy to Deserialization.

Upvotes: 6

Related Questions