假设我的JAVA类中有三个公共属性:
public int Rating = 0;
public int Scalability = 0;
public int Overview = 0;现在,我想使用gson来JSONify这个类的对象。但在执行此操作时,我想“转换”Overview属性的值。我想对字符串数组运行它的整数值,并加载相应的字符串。然后我希望生成的JSON如下:{"Rating":"1","Scalability":"2","Overview":"Text details from array"}
我知道我需要为int编写一个定制的序列化程序。但是如何确保它只针对Overview属性运行呢?
发布于 2014-05-31 00:04:37
为了让它工作,您必须将概述类型更改为枚举,并在GsonBuilder创建过程中为这个新枚举创建并注册一个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);
}https://stackoverflow.com/questions/23956899
复制相似问题