class A {
int common;
int forGSON1;
int forGSON2;
int forGSON3;
int forGSON12;
}
common
forGSON1
forGSON12
common
forGSON2
forGSON12
common
forGSON3
Gson
@Expose
Gson
.excludeFieldsWithoutExposeAnnotation()
Gson
transient
Gson
.excludeFieldsWithModifiers
hack
.excludeFieldsWithoutAnnotation(customAnnotation)
This can be achieved using custom exclude strategy. Here is the code.
1) Create custom exclude annotations
2) Create custom exclude strategy classes
3) Use the exclude strategy class while creating Gson object
Exclude Strategy Classes:-
public class Strategy1 implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Strategy1Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
public class Strategy2 implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Strategy2Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
public class Strategy3 implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Strategy3Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
Exclude Annotations:-
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Strategy1Exclude {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Strategy2Exclude {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Strategy3Exclude {
}
Class A:-
public class A {
int common;
@Strategy3Exclude
@Strategy2Exclude
int forGSON1;
@Strategy3Exclude
@Strategy1Exclude
int forGSON2;
@Strategy2Exclude
@Strategy1Exclude
int forGSON3;
@Strategy3Exclude
int forGSON12;
...
getters and setters
}
Main method:-
public static void main(String[] args) {
A a = new A();
a.setCommon(1);
a.setForGSON1(2);
a.setForGSON12(12);
a.setForGSON3(3);
a.setForGSON2(2);
Gson gsonStrategy1 = new GsonBuilder().setExclusionStrategies(new Strategy1()).create();
Gson gsonStrategy2 = new GsonBuilder().setExclusionStrategies(new Strategy2()).create();
Gson gsonStrategy3 = new GsonBuilder().setExclusionStrategies(new Strategy3()).create();
System.out.println(gsonStrategy1.toJson(a));
System.out.println(gsonStrategy2.toJson(a));
System.out.println(gsonStrategy3.toJson(a));
}
Output:-
{"common":1,"forGSON1":2,"forGSON12":12}
{"common":1,"forGSON2":2,"forGSON12":12}
{"common":1,"forGSON3":3}