我必须在不修改源代码的情况下序列化Java类。我正在使用GSON并获取"类Person声明了多个名为serialVersionUID"的JSON字段,因为Person的超类也有此字段。所以我想在序列化期间排除名为serialVersionUID的字段,以避免出现此错误(可以用于我的目的)添加以下代码:
g <- xtabs(dataset)
g
print(g)
然而,我仍然得到错误,无法理解超出它的原因。
以下是示例类层次结构:
GsonBuilder gsonBuilder = new GsonBuilder();
ExclusionStrategy excludePolicy = new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
return arg0.getName().contains("serialVersionUID");
}
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
};
gsonBuilder.addSerializationExclusionStrategy(excludePolicy);
gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
Gson gson = gsonBuilder.create();
Writer writer;
try {
writer = new FileWriter("fileLoc");
gson.toJson(personList, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
在分析了GSON的源代码之后,我能够自己提出解决方案。要排除字段,以免你得到&#34;类Person声明多个名为serialVersionUID&#34;的JSON字段;错误,您还应该添加反序列化排除策略:
gsonBuilder.addDeserializationExclusionStrategy(excludePolicy);
所以最终的代码是:
GsonBuilder gsonBuilder = new GsonBuilder();
ExclusionStrategy excludePolicy = new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes arg0) {
return arg0.getName().contains("serialVersionUID");
}
@Override
public boolean shouldSkipClass(Class<?> arg0) {
return false;
}
};
gsonBuilder.addSerializationExclusionStrategy(excludePolicy);
gsonBuilder.addDeserializationExclusionStrategy(excludePolicy);
gsonBuilder.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);
Gson gson = gsonBuilder.create();
Writer writer;
try {
writer = new FileWriter("fileLoc");
gson.toJson(personList, writer);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}