2012-10-04 95 views
1

我使用JSON-Simple在JSON中攝取推文。我分裂了用戶對象關到它自己的JSONObject類,內存:如何在JSON-Simple中處理空值?

incomingUser = (JSONObject) incomingTweet.get("user"); 

然後我剝離從鳴叫各個領域,並使用JSON-簡單的用戶對象;我是做

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。

我的三元陳述沒有解釋這個嗎?如果它是(condtion?是真的),它應該評估爲put("location","")否?雖然它會檢查它是否等於null(只有一個'空對象'應該能夠看到指針是相同的)。

我哪裏錯了?我應該怎麼做才能處理這個空值?

回答

3

你得到一個空指針異常,因爲你試圖訪問一個空對象的.equals()方法。

相反試試這個,如果location鍵返回值:

(incomingUser.get("location").toString() == null) ? etc.. 

編輯:其實它只是發生在我,也許incomingUser.get("location")返回null(即location關鍵可能是指一個JSONObjectJSONArray) ,在這種情況下,您需要:

(incomingUser.get("location") == null) ? etc... 
0

只需使用try and catch塊來處理它........

try{ 

strippedJSON.put("userLocation", incomingUser.get("location").toString(); 



}catch(Exception ex){ 

    System.out.println("This field is null"); 

} 
+0

Ol,當然,但將它合理地放入JSON文件中會更有意義嗎?這不是濫用'try {} catch(){}'塊嗎? – Pureferret

+1

@Pureferret到現在爲止,我所遇到的所有JSON都被提供給我的一些webservice ....所以JSON的編碼不在我的手中,但是我需要一些如何處理它。並嘗試着抓住它我做到了...... –

+0

@Pureferret整個Java是濫用'try {} catch(){}'塊 – Kevin