Gson忽略了序列化排除策略

时间:2018-01-26 16:28:12

标签: java gson

序列化

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 个答案:

答案 0 :(得分:2)

分析

看来,这是一个众所周知的问题:

一些替代解决方案

解决方案#1:使用类型适配器

那里推荐的解决方案(参见«分析»链接),解决方法是引入适当的类型适配器。

解决方案#2:从序列化中排除静态字段

为什么不排除静态字段的序列化?

new GsonBuilder()
    // ...
    .excludeFieldsWithModifiers(Modifier.TRANSIENT, Modifier.STATIC)
    // ...

解决方案#3:仅序列化@Exposed字段

可以使用@Exposed注释显式公开可序列化字段,并适当配置GsonBuilder

new GsonBuilder()
    // ...
    .excludeFieldsWithoutExposeAnnotation()
    // ...