I\'m trying to learn Gson and I\'m struggling with field exclusion. Here are my classes
public class Student {
private Long id;
privat
After reading all available answers I found out, that most flexible, in my case, was to use custom @Exclude
annotation. So, I implemented simple strategy for this (I didn't want to mark all fields using @Expose
nor I wanted to use transient
which conflicted with in app Serializable
serialization) :
Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}
Strategy:
public class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class> clazz) {
return false;
}
}
Usage:
new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();