GSON:针对特定属性的自定义序列化程序

时间:2014-05-30 14:23:24

标签: java gson

假设我的JAVA课程中有三个公共属性:

public int Rating = 0;
public int Scalability = 0;
public int Overview = 0;

现在,我想使用gson JSONify这个类的对象。但在这样做的同时,我希望"转换" Overview属性的值。我想对一个字符串数组运行其整数值并加载相应的字符串。 然后我希望JSON生成如下: {"评分":" 1","可扩展性":" 2","概述":"数组"}

中的文本详细信息

我知道我需要为int编写自定义序列化程序。但是如何确保它仅针对Overview属性运行?

1 个答案:

答案 0 :(得分:1)

为了使它能够工作,您必须将概述类型更改为Enum,并在GsonBuilder创建过程中为此新Enum创建并注册TypeAdapter。

因此,对于您的示例,您将拥有这样的类:

enum OverviewType {
    TYPE_0("Text details from array");
    public final String desc;

    private OverviewType(String desc) {
        this.desc = desc;
    }
}

class Example {
    public int Rating = 0;
    public int Scalability = 0;
    public OverviewType Overview = OverviewType.TYPE_0;

    public Example(int rating, int scalability, OverviewType overview) {
        super();
        Rating = rating;
        Scalability = scalability;
        Overview = overview;
    }

    public String toString() {
        return "Example [Rating=" + Rating + ", Scalability=" + Scalability
                + ", Overview=" + Overview + "]";
    }

}

OverviewType的此类型适配器:

class OverviewTypeAdapter extends TypeAdapter<OverviewType> {

    public void write(JsonWriter out, OverviewType value) throws IOException {
         if (value == null) {
              out.nullValue();
              return;
         }
         out.value(value.desc);
    }

    public OverviewType read(JsonReader in) throws IOException {
        String val = in.nextString();
        if(null == val) return null;

        for(OverviewType t : OverviewType.values()){
            if(t.desc.equals(val)) return t;
        }

        throw new IllegalArgumentException("Not a valid enum value");
    }

}

在GsonBuilder上注册TypeAdapter,如下所示:

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(OverviewType.class, new OverviewTypeAdapter())
            .create();

最终用法是这样的:

public void testGson2() {
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(OverviewType.class, new OverviewTypeAdapter())
            .create();

    // serializing
    String json = gson.toJson(new Example(1, 10, OverviewType.TYPE_0));
    System.out.println(json);

    // and deserializing
    String input = "{\"Rating\":5,\"Scalability\":20,\"Overview\":\"Text details from array\"}";
    Example example = gson.fromJson(input, Example.class);
    System.out.println(example);

}