2 mcd316 Mcd316 于 2013.07.24 15:36 提问

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类型的就失败?

1个回答

shaojie519
shaojie519   2013.07.24 16:34
已采纳

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

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!