有没有办法可以将int/short值转换为布尔值?我收到的JSON看起来像这样:
{ is_user: "0", is_guest: "0" }
Run Code Online (Sandbox Code Playgroud)
我正在尝试将其序列化为如下所示的类型:
class UserInfo {
@SerializedName("is_user")
private boolean isUser;
@SerializedName("is_guest")
private boolean isGuest;
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
如何让Gson将这些int/short字段转换为布尔值?
Jes*_*son 49
首先获取Gson 2.2.2或更高版本.早期版本(包括2.2)不支持基本类型的类型适配器.接下来,编写一个将整数转换为布尔值的类型适配器:
private static final TypeAdapter<Boolean> booleanAsIntAdapter = new TypeAdapter<Boolean>() {
@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);
}
}
};
Run Code Online (Sandbox Code Playgroud)
...然后使用此代码创建Gson实例:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.create();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7678 次 |
| 最近记录: |