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();