将整数转换为布尔值 [英] Convert ints to booleans
本文介绍了将整数转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法将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域转换为布尔值吗? 解决方案
首先获取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 {$ b $ 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();
返回null;
case NUMBER:
return in.nextInt()!= 0;
case STRING:
return Boolean.parseBoolean(in.nextString());
默认值:
抛出新的IllegalStateException(期望的BOOLEAN或NUMBER,但是+ peek);
}
}
};
...然后使用此代码创建Gson实例:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class,booleanAsIntAdapter)
.registerTypeAdapter(boolean.class,booleanAsIntAdapter)
.create();
Is there a way that I can convert int/short values to booleans? I'm receiving JSON that looks like this:
{ is_user: "0", is_guest: "0" }
I'm trying to serialize it into a type that looks like this:
class UserInfo {
@SerializedName("is_user")
private boolean isUser;
@SerializedName("is_guest")
private boolean isGuest;
/* ... */
}
How can I make Gson translate these int/short fields into booleans?
解决方案
Start by getting Gson 2.2.2 or later. Earlier versions (including 2.2) don't support type adapters for primitive types. Next, write a type adapter that converts integers to booleans:
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);
}
}
};
... and then use this code to create the Gson instance:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Boolean.class, booleanAsIntAdapter)
.registerTypeAdapter(boolean.class, booleanAsIntAdapter)
.create();
这篇关于将整数转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文