提问者:小点点

为什么名称排除策略不能防止“类声明多个名为XXX的JSON字段”错误?


我必须在不修改Java类源代码的情况下序列化它们。我使用GSON并得到“Person类声明了多个名为serialVersionUID的JSON字段”,因为Person的超类也有这个字段。因此,我想在序列化过程中排除名为serialVersionUID的字段,以避免此错误(这对于我的目的来说是可以的),并添加以下代码:

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();
}

然而,我仍然得到了错误,无法理解超出它的原因。

这是示例类层次结构:

public class Person extends SuperPerson {
    private static final long serialVersionUID = 1L;
}

public class SuperPerson {
    private  static final long serialVersionUID = 1L;
}

共1个答案

匿名用户

在分析了GSON的源代码后,我自己想出了解决方案。要排除字段以使您不会得到“class Person声明多个名为seralVersionUID的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();
}