2012-12-05 71 views
2

空響應我得到一個JSON響應,如何辦理JSON對象

{ 
"edges": [], 
"nodes": [] 
} 

如何檢查對象具有空值和處理的情況下?

JSONObject jobj = new JSONObject(line); 
JSONArray jArray = jobj.getJSONArray("edges"); 
if(jArray.length()!=0) 
{  
    for(int i=0;i<jArray.length();i++){ 
    JSONObject json_data = jArray.getJSONObject(i); 
    x.add((float) json_data.getInt("x")); 
    y.add((float) json_data.getInt("y")); 
end 

這retrurns我:org.json.JSONException:在

+1

難道這個異常拋在這一行嗎? 'JSONObject jobj = new JSONObject(line);'我懷疑你沒有解析你認爲你的響應,因爲異常消息表明你試圖解析一個空字符串。解析發生在你的第一行;其餘的都是絨毛。 – dokkaebi

回答

2

,您可以檢查爲:

JSONObject jobj = new JSONObject(line); 
if (jobj.getJSONArray("edges").length() == 0) { 

    System.out.println("JSONArray is null");  
} 
else{ 
     System.out.println("JSONArray is not null"); 
     //parse your string here   
    } 
+0

這不起作用。我嘗試過這個。它仍然顯示錯誤 – ChanChow

+0

它顯示的是什麼錯誤?因爲JSONObject中有兩個json數組,所以JSONObject不爲null。現在你只需要檢查JSONArray是否爲空 –

+0

org.json.JSONException:輸入結束在字符0的 – ChanChow

0

使用簡單的Java規則字符輸入0結束。檢查數組是否爲空,如果數組不存在,並嘗試獲取它,則返回null。處理它。如果知道它會失敗,請不要繼續解析。優雅地存在。

if (myObj != null) 
{ 
    ... process 
} 
3

試試這個:

String jsonString = "{ "edges": [], "nodes": [] }"; 

JSONObject jsonObject = new JSONObject(jsonString); 

if(jsonObject.isNull("edges") == false) { 
//do sth 
} 

if(jsonObject.isNull("nodes") == false) { 
//do sth 
} 

你也可以檢查您是否已經通過jsonObject.has在你的JSON一些特定的按鍵(「邊緣「)

您正在將一些\ line \變量傳遞給JSONObject構造函數。確保這個變量包含你的整個json字符串,就像我在這個例子中的那樣,而不是像 「{」或'「邊緣」:[]'可能問題出現在你的json源碼中,如dokkaebi在評論中建議

+0

是U相信這會工作,因爲參考isNull只檢查重點是存在的JSONObject或不 –

+0

的isNull檢查鍵存在,或者如果它具有空值 有()方法只檢查一些重要的存在 這是什麼文件說,「確定如果與該鍵關聯的值爲空或者沒有值。「 – fgeorgiew

2

試試這個。我僅根據標誌值顯示僅針對一個數組的示例,您可以顯示正確的錯誤消息或成功時,可以將分析的數據綁定到UI組件。

String impuStr = "{\"edges\": [],\"nodes\": []}"; 

String flag = serverResponse(impuStr);

private String serverResponse(String jsonStr) { String flag =「success」;

JSONObject jobj; 
    try { 
     jobj = new JSONObject(jsonStr); 

     JSONArray jArrayEdges = jobj.getJSONArray("edges"); 
     if(jArrayEdges != null && jArrayEdges.length() > 0) 
     {  
      for(int i=0;i<jArrayEdges.length();i++) 
      { 
       JSONObject json_data = jArrayEdges.getJSONObject(i); 
       // process data here 
      } 
     }else 
      flag = "edges_list_empty"; 

    } catch (JSONException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     flag = "failure"; 
    } 

    return flag; 
}