2016-02-29 9 views
-4

我有JSON字符串像這樣:解析我的Android應用中的JSON時出錯?

{ 
    "listResult": { 
    "items": [ 
     { 
     "id": "629047db-66d9-4986-ba3f-c75554198138", 
     "thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/629047db-66d9-4986-ba3f-c75554198138/8cb69c17-0fdb-454c-bfb5-a5b9001a9d59.jpg" 
     }, 
     { 
     "id": "fa872dc8-d2b3-4815-92ef-d90e903bc3d8", 
     "thumbnail": "http://maya-wdv-01.r.worldssl.net/39aa32db-6f50-4da1-8fd5-a5b001135b98/fa872dc8-d2b3-4815-92ef-d90e903bc3d8/c510c24f-5bfd-4a64-8851-a5b90017a38d.jpg" 
     } 
    ], 
    "totalItems": 34, 
    "pageSize": 5, 
    "pageNumber": 1, 
    "totalPages": 7, 
    "searchTerm": null 
    } 
} 

我嘗試用代碼解析:

try { 
      JSONObject json = new JSONObject(response); 
      String listResult = json.getString(Variabel.listResult); 
      JSONArray items_obj = json.getJSONArray(Variabel.items); 
      int jumlah_list_data = items_obj.length(); 
      if (jumlah_list_data > 0) { 
       for (int i = 0; i < jumlah_list_data; i++) { 
        JSONObject obj = items_obj.getJSONObject(i); 
        String id = obj.getString(Variabel.id); 
        String thumbnail = obj.getString(Variabel.thumbnail); 

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

但我得到錯誤:

org.json.JSONException:物品沒有價值

那麼如何解決呢?對不起,我的英語

回答

2

相反的:

JSONObject json = new JSONObject(response); 
String listResult = json.getString(Variabel.listResult);    
JSONArray items_obj = json.getJSONArray(Variabel.items); 

你應該有:

JSONObject json = new JSONObject(response); 
    JSONObject listResult = json.getJSONObject(Variabel.listResult); 
    JSONArray items_obj = listResult.getJSONArray(Variabel.items); 
+0

感謝先生:d ... –

2

因此給您發佈的JSON,項目是listResult直接孩子,所以你必須使用JSONObject與關鍵listResult進行檢索。更改

JSONArray items_obj = json.getJSONArray(Variabel.items); 

JSONArray items_obj = listResult.getJSONArray(Variabel.items);