为了使其工作,您必须将概览类型更改为 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);
}