2016-05-02 16 views
0

我有一個Android應用程序調用REST Web服務並獲取JSON答案。 當我輸入一個錯誤的參數時,我可以毫無問題地捕獲錯誤,但有時JSON上的某些結果爲空。我怎樣才能捕捉到這種情況?如何在Android上捕獲JSON空結果?

我的Android代碼:

try { 
    JSONObject jsonObj = new JSONObject(results); 

    JSONArray result = jsonObj.getJSONArray("result"); 

    for (int i = 0; i < result.length(); i++) { 
     JSONObject c = result.getJSONObject(i); 

     String string04 = c.getString("string04"); 
     String string05 = c.getString("string05"); 

     TextView txt1 = (TextView)findViewById(R.id.textView1); 
     txt1.setText(string04); 

     TextView txt2 = (TextView)findViewById(R.id.textView2); 
     txt2.setText(string05); 


     JSONArray dest = c.getJSONArray("dest"); 

     for (int o = 0; o < dest.length(); o++) { 

      JSONObject d = dest.getJSONObject(o); 

      JSONArray pred = d.getJSONArray("pred"); 

      for (int u = 0; u < pred.length(); u++) { 

       JSONObject e = pred.getJSONObject(u); 

       String string13 = e.getString("string13"); 
       TextView txt4 = (TextView)findViewById(R.id.textView4); 
       txt4.setText(string13); 
      } 
     } 
    } 
} catch (JSONException e) { 
    e.printStackTrace(); 
    Log.d("error", e.getMessage()); 
} 

一個好的JSON的結果會是這樣:

{ 
    "result": [{ 
     "string01": "104", 
     "string02": "104 - blablabla", 
     "string03": "104", 
     "string04": "blobloblo", 
     "string05": "blablabla", 
     "dest": [{ 
      "pred": [{ 
       "time": 1461348846, 
       "sec": 102, 
       "min": 1, 
       "string11": "514-String", 
       "string12": "Some String", 
       "string13": "Some other String", 
       "number": 0 
      }] 
     }] 
    }] 
} 

但有時,當沒有數據顯示,我得到的是這樣的:

{ 
    "result": [{ 
     "string01": "104", 
     "string02": "104 - blablabla", 
     "string03": "104", 
     "string04": "blobloblo", 
     "string05": "blablabla", 
     "dest": [{"pred":[]}] 
    }] 
} 
+1

只需測試相應的JSONArray對象的長度,一個空數組的大小爲0. –

+0

如果列表爲空,則永遠不會輸入遍歷'pred'數組的循環,所以我認爲您不能獲得空值。 –

回答

0

解析器JSON具有「opt」方法,將返回NULL如果沒有匹配條件的對象。這些方法與獲取方法類似。

E.g:getJSONObject("column")throwexception如果沒有爲「column

optJSONObject("column")只會返回一個NULL值,如果不存在,它的值。我個人發現在使用JSONs時可以方便地使用「opt」方法,這些方法的值在運行時可能會丟失。