在这种情况下,我有两个具有 GSON 实现的类,一个是 A,另一个是 B,
Class A {
@SerializedName("x")
@Expose
private String x;
@SerializedName("y")
@Expose
private String y;
...
}
class B extends A{
@SerializedName("x")
@Expose
private List<String> x;
@SerializedName("z")
@Expose
private String z;
...
}
问题是两个类都需要在那里有序列化名称 x 字段,并且不能对类 A 进行任何更改,因为它被其他一些类使用,因此当类 B 序列化时,由于多个变量,它会给出错误一个序列化的名称。对此的最佳解决方案是什么?根据我的理解,GSON 排除策略不起作用,因为它总是会跳过父 x。
最佳答案
序列化 B
时需要使用 ExclusionStrategy
,但序列化 A
时不需要。所以只需创建 2 个 Gson
对象即可。
排除策略
使用时将忽略 A.x
。
class MyExclusionStrategy implements ExclusionStrategy {
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
public boolean shouldSkipField(FieldAttributes field) {
return field.getDeclaringClass().equals(A.class) &&
field.getName().equals("x");
}
}
给定这两个对象:
A a = new A();
a.setX("xValue");
a.setY("yValue");
和
B b = new B();
b.setX(Arrays.asList("a", "b"));
b.setY("yValue");
b.setZ("zValue");
序列化a
Gson gson = new GsonBuilder().create();
String aAsJsonString = gson.toJson(a);
System.out.println(aAsJsonString);
输出:
{"x":"xValue","y":"yValue"}
序列化b
Gson gson = new GsonBuilder()
.setExclusionStrategies(new MyExclusionStrategy())
.create();
String bAsJsonString = gson.toJson(b);
System.out.println(bAsJsonString);
输出:
{"x":["a","b"],"z":"zValue","y":"yValue"}
关于java - 在选定执行时跳过父类中的 gson 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49296033/