序列化
public class Subclass extends Superclass {
private static final long serialVersionUID = 1L;
private int someProperty;
public Subclass() {
}
public Subclass(int someProperty, String myProperty) {
super(myProperty);
this.someProperty = someProperty;
}
public int getSomeProperty() {
return someProperty;
}
public void setSomeProperty(int someProperty) {
this.someProperty = someProperty;
}
}
与
public class Superclass implements Serializable {
private static final long serialVersionUID = 1L;
private String myProperty;
public Superclass() {
}
public Superclass(String myProperty) {
this.myProperty = myProperty;
}
public String getMyProperty() {
return myProperty;
}
public void setMyProperty(String myProperty) {
this.myProperty = myProperty;
}
}
不应该因为
而失败Exception in thread "main" java.lang.IllegalArgumentException: class richtercloud.gson.exclusion.strategy.Subclass declares multiple JSON fields named serialVersionUID
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:170)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.toJson(Gson.java:661)
at com.google.gson.Gson.toJson(Gson.java:648)
at com.google.gson.Gson.toJson(Gson.java:603)
at com.google.gson.Gson.toJson(Gson.java:583)
at richtercloud.gson.exclusion.strategy.Main.main(Main.java:41)
如果使用序列化排除策略如下:
Gson gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.TRANSIENT)
.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes f) {
boolean retValue = f.getName().equals("serialVersionUID");
return retValue;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
})
.create();
Subclass a = new Subclass();
String response = gson.toJson(a);
System.out.println(response);
我正在使用Gson 2.8.2。
答案 0 :(得分:2)
看来,这是一个众所周知的问题:
那里推荐的解决方案(参见«分析»链接),解决方法是引入适当的类型适配器。
为什么不排除静态字段的序列化?
new GsonBuilder()
// ...
.excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC)
// ...
@Exposed
字段可以使用@Exposed
注释显式公开可序列化字段,并适当配置GsonBuilder
:
new GsonBuilder()
// ...
.excludeFieldsWithoutExposeAnnotation()
// ...