2014-02-10 31 views
0

我的數組訪問內部數組的JSON數組是如何從Android

{ 
    newsitem [ 
       {"headline":"hello","caption":"date", 

        "image":{"photo":"img","thumb":"thumbnail"} 
      } 
      ] 
} 

我想用的JSONObject和jsonarray訪問照片和拇指。我可以訪問標題和標題。

這是我用來獲取標題的代碼。幫助我得到照片和拇指。

JSONObject obj = new JSONObject(retstring); 
       JSONArray ja = obj.getJSONArray("NewsItem"); 

for (int i = 0; i < ja.length(); i++) { 

        JSONObject jo = (JSONObject) ja.get(i); 


String h=jo.getString("HeadLine"); 

} 
+0

是完整的JSON數據? –

回答

1

imageJSONObject而不是JSONArray這樣你可以得到photothumb值:

for (int i = 0; i < ja.length(); i++) { 

JSONObject jo = (JSONObject) ja.get(i); 

    String h=jo.getString("HeadLine"); 
    // get image JSONObject from jo 
    JSONObject jsonimage=jo.optJSONObject("image"); 

    // get photo anf thumb values from jsonimage jsobobject 
    String str_photo=jsonimage.optString(photo); 
    ... 
} 
3

你可以試試下面的示例:

JSONObject new_jo = jo.getJSONObject("image"); 
    String pic = new_jo.getString("photo"); 
    String thumbnail = new_jo.getString("thumb"); 
2

你錯了。 圖片標籤不是JsonArray。它是JsonObject。所以使用這個。

for (int i = 0; i < ja.length(); i++) { 

    JSONObject jo = (JSONObject) ja.get(i); 

    String headline =jo.getString("HeadLine"); 

    JSONObject jsonimage=jo.optJSONObject("image"); 


    String str_photo=jsonimage.optString("photo"); 

} 
0
Follow these steps in order to parse the json 
1) Create JSONObject for getting the result string. 
2) Create JSONArray for getting array from "newsitem" tag 
3) Create JSONObject for 
    3.1) headline tag 
    3.2) caption tag 
    3.3) image tag 
4) Create again JSONObject for 
    4.1) photo tag 
    4.2) thumb tag 


Now how to achieve this 

JSONObject jsonObj=new JSONObject(jsonstring); 
JSONArray newsItemObj=jsonObj.getJSONArray("newitem"); 

for(int i=0;i<newsItemObj.length();i++) 
{ 
    String headline=newsItemObj.getString("headline"); 
    String caption=newsItemObj.getString("caption"); 

    JSONObject imageObject=newsItemObj.getJSONObject("image"); 

    String photo=imageObject.getString("photo"); 
    String thumb=imageObject.getString("thumb"); 

}