Gson解析boolean值的注意

<span style="font-size:18px;">public class GsonUtils {
	public static <T> T changeGsonToBean(String gsonString, Class<T> cls) {
		Gson gson = new Gson();
		T t = gson.fromJson(gsonString, cls);
		return t;
	}}</span>


<span style="font-size:18px;">public class Test {
	public static void main(String[] args) {
		String str = "{\"focus\":\"1\", \"name\":\"zhangsan\"}";
		Person person = GsonUtils.changeGsonToBean(str, Person.class); 
		
		System.out.println(person.focus);
	}
}</span>
打印出来一直是false。


正确的做法:

<span style="font-size:18px;">public class Test {
	public static void main(String[] args) {
		String str = "{\"focus\":true, \"name\":\"zhangsan\"}";
		Person person = GsonUtils.changeGsonToBean(str, Person.class); 
		
		System.out.println(person.focus);
	}
}</span>
这样子能正确的输出true。


http://stackoverflow.com/questions/11399079/convert-ints-to-booleans

Convert ints to booleans

up vote 10 down vote favorite
4

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?

share | improve this question
 

2 Answers

active oldest votes



up vote 13 down vote accepted

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();
share | improve this answer


总结:每次搜到stackoverflow上的解答,感觉人家是从源头上解决问题。羡慕!




你可能感兴趣的:(Gson解析boolean值的注意)