问题描述
- Android Gson转换问题
-
import android.R.bool;public class WebServerData { /// /// 返回数据 /// public String data;
/// <summary> /// 提示消息 /// </summary>
public String msg ;
/// <summary> /// 是否成功 /// </summary>
public bool success ;
public String getData() { return data; }
public void setData(String data) { this.data = data; }
public String getMsg() { return msg; }
public void setMsg(String msg) { this.msg = msg; }
public bool getSuccess() { return success; }
public void setSuccess(bool success) { this.success = success; } }
转换:
String d = msg.getData().getString("data"); Gson gson = new Gson();
gson.fromJson(d, WebServerData.class);
问题:问什么把对象中bool类型的参数去掉转换成功,有bool类型的就失败?
解决方案
public class JsonBooleanDeserializer implements JsonDeserializer{
@Override
public Boolean deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
String value = json.getAsJsonPrimitive().getAsString();
return value.toLowerCase().equals("true");
} catch (ClassCastException e) {
throw new JsonParseException("Cannot parse json date '" + json.toString() + "'", e);
}
}
}
boolean类型需要自己去构造解析("true"->true 或者 "1"->true),自己选择boolean的解析
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Boolean.class, new JsonBooleanDeserializer());
Gson gson = builder.create();