[英]How to handle a null value in JSON-Simple?
我正在使用JSON-Simple接收JSON中的推文。 我在內存中將用戶對象拆分為它自己的JSONObject類:
incomingUser = (JSONObject) incomingTweet.get("user");
然后,我使用JSON-Simple從推文和用戶對象中剝離各個字段; 我在做
strippedJSON.put("userLocation", incomingUser.get("location").toString();
但是事實證明,有時用戶的位置設置為null
。
因此,現在我要檢查要剝離的字段是否為空,並將其設置為“”:
strippedJSON.put("userLocation", (incomingUser.get("location").toString().equals(null)?
"": incomingUser.get("location").toString());
但是我在調試模式下瀏覽了eclipse,發現某人的location設置為null,然后跳過了我刪除與"location"
關聯的JSON對象字段並將其放入JSON對象字段"user Location"
。 我得到了NPE。
我的三元陳述不解釋這一點嗎? 我本來會檢查它是否等於null(只有一個“ null對象”,它應該能夠看到指針是相同的),如果它是( condtion?
是true),則應評估為put("location","")
不?
我要去哪里錯了? 我應該怎么做才能處理這個空值?
由於嘗試訪問空對象上的.equals()方法,因此獲得了空指針異常。
如果location
鍵返回一個值,請嘗試以下操作:
(incomingUser.get("location").toString() == null) ? etc..
編輯:實際上,它只是發生在我身上,也許incomingUser.get("location")
返回null
(即, location
鍵可能是指向JSONObject
或JSONArray
),在這種情況下,您需要:
(incomingUser.get("location") == null) ? etc...
只需使用try and catch
塊來處理它。
try{
strippedJSON.put("userLocation", incomingUser.get("location").toString();
}catch(Exception ex){
System.out.println("This field is null");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.