想试试用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();
可以解决,但是我试过了,没用。
黄舟2017-04-17 13:32:06
Post an answer from google+ and replace null with ""
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();
}
}
Then use it like this:
GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(String.class, new StringConverter());
Gson gson = gb.create();
迷茫2017-04-17 13:32:06
This kind of problem is an ordinary Java null pointer. Your object is null. Calling its get method will definitely result in a null pointer. The remedy is to add judgment or modify the data source
黄舟2017-04-17 13:32:06
If the server cooperates with you, just change it to "" an empty string when encountering a null value.
If you can only change it locally, you have to make a judgment every time, and you cannot use Gson to analyze it
if (dataObject.has("id") && !dataObject.isNull("id")) {
dataObject.getString("id"));
}
迷茫2017-04-17 13:32:06
This is not Gson’s problem at all. . . .
The value that is obviously yours is null.
So your sentence
Log.e("这是什么鬼", old_info.getLovecode());
is equivalent to
Log.e("这是什么鬼", null);
If you change it to
Log.e("这是什么鬼", old_info.getLovecode()!=null?old_info.getLovecode():"");
It won’t be wrong. If I am wrong, hit me.