有没有办法可以将int / short值转换为布尔值?我收到的JSON看起来像这样:
{ is_user: "0", is_guest: "0" }
我正在尝试将其序列化为如下所示的类型:
class UserInfo {
@SerializedName("is_user")
private boolean isUser;
@SerializedName("is_guest")
private boolean isGuest;
/* ... */
}
如何让Gson将这些int / short字段翻译成布尔值?
答案 0 :(得分: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);
}
}
};
...然后使用此代码创建Gson实例:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.create();
答案 1 :(得分:0)
如果你是以整体或短片的形式阅读它们,那么你可以
boolean b = (i != 0)
其中b是你想得到的布尔值,i是int或short值。
如果您正在以字符串形式阅读它们,那么您需要
boolean b = !s.equals("0"); // use this if you WANT null pointer exception
// if the string is null, useful for catching
// bugs
或
boolean b = !"0".equals(s); // avoids null pointer exception, but may silently
// let a bug through