2017-05-04 170 views
0

當我使用如何從Java中的JSONObject獲取值?

jitem.getString("firstitem"); 

jitem.getJSONObject("firstitem"); 

jitem.get("firstitem"); 

以下是代碼片段我試圖解析JsonArray並獲得其價值,但我gettign錯誤。

JSONArray arr_items = new JSONArray(str); 
     if(arr_items!=null && arr_items.size()>0){ 

      for(int i=0;i<arr_items.size();i++){ 
      JSONObject jitem = arr_items.getJSONObject(i);//works fine till here 
      jitem.getString("firstitem"); //throws exception here 
      } 

這是我解析

[{"firstitem":"dgfd","secondtitem":"dfgfdgfdg","thirditem":"[email protected]","fourthitem":"jkksdjklsfjskj"}] 

我在做什麼錯JSONArray?如何通過使用鍵來獲取這些值?

更新:說明該數組及其參數根本不爲空。他們都有有效的價值。

+0

什麼是例外? – Henry

+0

你正在使用哪個json庫?既然你有org.json和org.json.simple的混合方法 –

+0

@SachinGupta我正在使用org.apache.commons.json –

回答

0

首先檢查arr_items不是空的。 然後,嘗試用的try/catch周圍的片段:

try { 
     your snippet 

     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
+0

這是如何解決問題的?它避免了一個例外,但仍然沒有價值。 – Henry

+0

在Android Studio中,如果我不嘗試圍繞/捕獲這個類型片斷,編輯給予警告,我必須得圍繞着它。也許,他可以試試 –

0

檢查以下

String json ="{'array':" + "[{'firstitem':'dgfd','secondtitem':'dfgfdgfdg','thirditem':'[email protected]','fourthitem':'jkksdjklsfjskj'}]"+ "}"; 
    JSONObject myjson = new JSONObject(json); 
    JSONArray the_json_array = myjson.getJSONArray("array"); 

    int size = the_json_array.length(); 
// ArrayList<JSONObject> arrays = new ArrayList<JSONObject>(); 
    for (int i = 0; i < size; i++) { 
     JSONObject another_json_object = the_json_array.getJSONObject(i); 
    // arrays.add(another_json_object); 
     System.out.println(another_json_object.get("firstitem")); 
    } 

它需要一些數組名稱,以便追加數組名吧,如果你想沒有它,你必須添加GSON 。