上周五,在解析json中遇到一个很坑的问题,就是解析Json字符串时出现value为null的时候,出现空指针异常。当时让
String password = jsonObject.get("password").getAsString();
JsonElement passwordJsonEle = jsonObject.get("password");
if(passwordJsonEle!=null){
String password = passwordJsonEle.getAsString();
System.out.println(password);
}
发现会进入if语句块,所以比较奇怪,查看源码,发现Gson解析Gson时底层解析的key:value是用Map装取,而当vaule为null时则装入的是Gson自定义的JsonNull类对象。
源代码:
/**
* Adds a member, which is a name-value pair, to self. The name must be a String, but the value
* can be an arbitrary JsonElement, thereby allowing you to build a full tree of JsonElements
* rooted at this node.
*
* @param property name of the member.
* @param value the member object.
*/
public void add(String property, JsonElement value) {
if (value == null) {
value = JsonNull.INSTANCE;
}
members.put(property, value);
}
下面是测试代码
public class GsonIsNull {
public static void testIsNull(){
Gson gson = new Gson();
String jsonString = "{\"name\":\"毛豆豆\",\"age\":24,\"password\":null}";
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String name = jsonObject.get("name").getAsString();
System.out.println(name);
String password = jsonObject.get("password").getAsString();
//空指针异常
//JsonElement passwordJsonEle = jsonObject.get("password");
//if(passwordJsonEle!=null){
//String password = passwordJsonEle.getAsString();
//System.out.println(password);
//}
//正常
JsonElement passwordJsonEle = jsonObject.get("password");
if(!passwordJsonEle.isJsonNull()){
String password = passwordJsonEle.getAsString();
System.out.println(password);
}
2017.3.14