序列化
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。
1条答案
按热度按时间np8igboo1#
分析
看来,这是一个众所周知的问题:
与java.sql.resultset·issue#464·google/gson·github集成。
将对象转换为json·issue#399·google/gson·github时出错。
一些替代方案
解决方案1:使用类型适配器
建议的解决方案(参见«分析» 链接),解决方法是引入适当的类型适配器。
解决方案2:从序列化中排除静态字段
为什么不排除静态字段的序列化呢?
解决方案3:仅序列化@exposed字段
通过使用
@Exposed
注解和配置GsonBuilder
适当地: