首先得到Gson 2.2.2或更高版本。早期版本(包括2.2)不支持基本类型的类型适配器。接下来,编写一个将整数转换为布尔值的类型适配器:
private static final TypeAdapter booleanAsIntAdapter = new TypeAdapter() {
@Override public void write(JsonWriter out, Boolean value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value);
}
}
@Override public Boolean read(JsonReader in) throws IOException {
JsonToken peek = in.peek();
switch (peek) {
case BOOLEAN:
return in.nextBoolean();
case NULL:
in.nextNull();
return null;
case NUMBER:
return in.nextInt() != 0;
case STRING:
return Boolean.parseBoolean(in.nextString());
default:
throw new IllegalStateException("Expected BOOLEAN or NUMBER but was " + peek);
}
}
};
…然后使用此代码创建Gson实例:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.create();