我正在使用JSON-Simple来摄取JSON中的tweet。我在内存中将user对象拆分到它自己的JSONObject类中:
incomingUser = (JSONObject) incomingTweet.get("user");然后,我使用JSON-Simple从tweet和user对象中剥离了各种字段;
strippedJSON.put("userLocation", incomingUser.get("location").toString();但事实证明,偶尔会将用户的位置设置为null。
strippedJSON.put("userLocation", (incomingUser.get("location").toString().equals(null)?
"": incomingUser.get("location").toString());但我已经在调试模式下浏览过eclipse,发现有人的位置设置为空,并跳过了与"location"关联的JSON对象字段并将其放入JSON对象字段"user Location"中的部分。我得了个NPE。
我的三元语句没有说明这一点吗?我会检查它是否等于null (只有一个'null对象‘,它应该能够看到指针是相同的),如果是(condtion?为真),它应该计算为put("location","") no?
我哪里错了?我应该做什么来处理这个空值呢?
发布于 2012-10-04 23:44:35
由于您正在尝试访问空对象上的.equals()方法,因此将出现Null指针异常。
如果location键返回一个值,请尝试执行以下操作:
(incomingUser.get("location").toString() == null) ? etc..编辑:实际上我刚刚想到incomingUser.get("location")可能会返回null (即.location密钥可能指的是JSONObject或JSONArray ),在这种情况下,您需要:
(incomingUser.get("location") == null) ? etc...发布于 2012-10-04 22:51:59
只需使用try and catch块来处理即可。
try{
strippedJSON.put("userLocation", incomingUser.get("location").toString();
}catch(Exception ex){
System.out.println("This field is null");
}https://stackoverflow.com/questions/12729954
复制相似问题