有一个项目需求,是解析一个json,其中父节点为’data’,子节点为不确定的key(即代码中的nowKey),次子节点为’had’.要将次子节点’had’下的数据封装到实体类中.
但次子节点had有时不存在,此时直接获取会空指针异常.
我尝试使用fastjson的jsonNode对象的’isEmpty’和’isNull’方法来判断该次子节点’had’是否存在,可是即使不存在,也会返回为true.
为此苦恼了好久,后来经过尝试,发现直接通过’==null’就能成功准确的判断该次子节点是否存在.
代码示例如下:
if (jsonnodeObj.get("data").get(nowKey).get("had")!=null){
newMatchObj.setZs(jsonnodeObj.get("data").get(nowKey).get("had").get("h").toString().replaceAll("\"","" ));
newMatchObj.setZp(jsonnodeObj.get("data").get(nowKey).get("had").get("d").toString().replaceAll("\"","" ));
newMatchObj.setZf(jsonnodeObj.get("data").get(nowKey).get("had").get("a").toString().replaceAll("\"","" ));
}else {
System.out.println("为空..........................");
newMatchObj.setZs("-");
newMatchObj.setZp("-");
newMatchObj.setZf("-");
}