关于Gson解析json数据时如果属性值为null则会报空的问题
想试试用Gson来解析json数据
这是data_info
{"careingpeople_id":"33","lovecode":null,"appellation":"父亲","name":"王健林","birthday":"2015-04-08","mobile":"15689653698","areano":"320583","communityno":"1","communityname":"测试小区","agency_id":"1","street":"","canselfcare":"0","language":"本地话","disease":"糖尿病","memo":"哈哈","ctime":"2015-04-08 10:22:33"}
这是解析的方法
old_man_info_data = GsonUtil.getInstance().fromJson(data_info, OldManInfoData.class);
其中json数据中有一个字段的值是null
"lovecode":null
此时如果执行如下代码,就会报错
Log.e("这是什么鬼", old_info.getLovecode());
这是错误
Caused by: java.lang.NullPointerException: println needs a message
想请问一下,有人碰到过类似问题吗?如何解决?
谢谢!
补充:Google了一下,有人说用下边这段代码
gson=new GsonBuilder().serializeNulls().create();
可以解决,但是我试过了,没用。
CHASY愁
9 years, 10 months ago
Answers
贴一个 google+ 的答案,将null替换成""
import java.lang.reflect.Type;
public class StringConverter implements JsonSerializer<String>,
JsonDeserializer<String> {
public JsonElement serialize(String src, Type typeOfSrc,
JsonSerializationContext context) {
if ( src == null ) {
return new JsonPrimitive("");
} else {
return new JsonPrimitive(src.toString());
}
public String deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return json.getAsJsonPrimitive().getAsString();
}
}
然后这么用:
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(String.class, new StringConverter());
Gson gson = gb.create();
芙蓉姐姐求交往
answered 9 years, 10 months ago