Unable to evaluate the expression Method threw ‘net.sf.json.JSONException’ exception.
序列化JSON字符串,JSON中存储的值是null,通过get()方法获取到值后,为空判断得到的结果居然是false
对于不了解的同事来说:这个很坑…
public static void main(String[] args) {
String str = "{\"Content\":null}";
JSONObject jsonObject = JSONObject.fromObject(str);
Object content = jsonObject.get("Content");
boolean isNull = (null == content);
// 期望结果:true,实际输出结果:false
System.out.println(isNull);
}
之所以会有这种情况,是因为JSONObject.formObject()方法对参数进行序列化的时候对值为null字符串的进行了处理,大致处理如下:
- 判断值是否为"null"字符串;如果是则见第二步;
- 创建一个JSONObject,并且对象中的元素nullObject = true;
- 把原本的null值替换为第二步创建的对象。
解决方案:使用net.sf.json.JSONUtils.isNull()
public static void main(String[] args) {
String str = "{\"Content\":null}";
JSONObject jsonObject = JSONObject.fromObject(str);
Object content = jsonObject.get("Content");
// boolean isNull = (null == content);
// 把原本的为空判断替换为:net.sf.json.JSONUtils.isNull()
boolean isNull = JSONUtils.isNull(content);
// 期望结果:true,实际输出结果:true
System.out.println(isNull);
}