概述
在使用google.gson
工具时,JsonElement
的getAsString()
方法返回JsonNull
异常问题。
问题描述
使用google.gson
工具时经常会使用的就是反序列化功能。比如看下面的一个方法:
private static JsonParser parser= new JsonParser();
public String parseJsonString(String raw) {
JsonElement jsonElement = JSON_PARSER.parse(raw);
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonElement dataType = jsonObject.has("dataType")? jsonObject.get("dataType"): null;
if(dataType != null) {
return jsonObject.get("dataType").getAsString();
}
return "null";
}
上述代码执行到if
语句处会判定dataType != null
,实际上这个判断根本就无法过滤json
为null
的情况,比如有如下的json
数据:
{
"dataType": null
}
下述代码返回的结果为:
JsonElement dataType = jsonObject.has("dataType")? jsonObject.get("dataType"): null;
//因为json数据中有"dataType"键,所以jsonObject.has("dataType")会返回true,那么dataType的值就是jsonObject.get("dataType")的值,也就是上述json数据中的所谓的null
dataType
实际上并不是所谓的java
中的null
,而是一种json
所表征的null
,它既不是字符串,同时dataType!=null
会判为true
,因为dataType
中是存有数据的,它存的是一种表征json
值为null
的数据,因为dataType!=null
会判为true
,然后会进入if
条件语句块执行getAsString()
,那么此时会报JsonNull
的异常。所以上述的判断语句不能只用dataType != null
来做判断条件,还需要加一条专门用来判断json
为null
的语句,即:isJsonNull()
方法,这是JsonElement
类的非静态方法。所以下述条件判断才是正确的:
if(dataType != null && !dataType.isJsonNull()) {
return jsonObject.get("dataType").getAsString();
}
//这一次则无法进入if语句块内部,因为:
dataType.isJsonNull()返回true,则
!dataType.isJsonNull()返回false