【问题标题】:GSON: Custom serializer for a specific propertyGSON:特定属性的自定义序列化程序
【发布时间】:2014-05-30 14:23:23
【问题描述】:

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

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

现在,我想使用 gson 对此类的对象进行 JSON 化。但是在这样做的同时,我想“转换” Overview 属性的值。我想针对一个字符串数组运行它的整数值并加载相应的字符串。 然后我希望生成的 JSON 像: {"Rating":"1", "Scalability":"2", "Overview": "Text details from array"}

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

【问题讨论】:

  • 针对定义值的类编写序列化程序然后设置概览字段不是更有意义吗?
  • 我不太确定你在这里的建议。更多细节或示例可能会有所帮助。

标签: java gson


【解决方案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);

}

【讨论】:

    猜你喜欢
    • 2011-10-14
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2019-05-16
    • 2015-07-27
    • 2013-09-09
    • 2013-03-09
    相关资源
    最近更新 更多