Reputation: 5166
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
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
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