2015-04-03 36 views
-3

讓我們假設我們有以下JSON格式,這有點複雜。適用於Android的JSON解析

items: [ 
{ 
    kind: "customsearch#result", 
    title: "Flower - Wikipedia, the free encyclopedia", 
    htmlTitle: "<b>Flower</b> - Wikipedia, the free encyclopedia", 
    link:  
    "http://upload.wikimedia.org/wikipedia/commons/a/a5/Flower_poster_2.jpg", 
    displayLink: "en.wikipedia.org", 
    snippet: "Flower - Wikipedia, the free", 
    htmlSnippet: "<b>Flower</b> - Wikipedia, the free", 
    mime: "image/jpeg", 

    image: { 
    contextLink: "http://en.wikipedia.org/wiki/Flower", 
    height: 5932, 
    width: 4462, 
    byteSize: 4487679, 
    thumbnailLink: "https://encrypted-tbn3.gstatic.com/images? 
    q=tbn:ANd9GcQdv1k3rb2HdBbQy9rEt_LX-PNnOd9uZ-O0PExeAJQfgoPxUna6pzS6ivfU", 
    thumbnailHeight: 150, 
    thumbnailWidth: 113 
    } 

} 
] 

我也有以下簡單的類。

public class WebImage { 

private String mUrl; 
private String mThumbnailUrl; 

public WebImage(String url, String thumbnailUrl) { 
    mUrl = url; 
    mThumbnailUrl = thumbnailUrl; 
} 

public String getUrl() { 
    return mUrl; 
} 

public String getThumbnailUrl() { 
    return mThumbnailUrl; 
} 

@Override 
public String toString() { 
    return mUrl + " | " + mThumbnailUrl; 
} 
} 

我對「items」JSON數組感興趣。數組中的每個項目都包含一個圖像「鏈接」和一個帶有「thumbnailLink」的「圖像」JSON對象。

private static List<WebImage> parseJsonResponse(String jsonResponse) throws 
JSONException { 

    List<WebImage> webImages = new ArrayList<WebImage>(); 

    // TODO: perform the parsing. 



    return webImages; 
} 

我該如何讀取物體?我對這個有點困惑。

謝謝

Theo。

回答

1

itemsJSONArrayJSONObject,並且每個JSONObject都包含image JSONObject。同時獲得linkthumbnailLink

JSONArray array =new JSONArray(jsonResponse); 
List<WebImage> webImages = new ArrayList<WebImage>(); 
for(int n = 0; n < array.length(); n++) 
{ 
    JSONObject object = array.getJSONObject(n); 
    // get link from object 
    String strLink= object.optString("link"); 
    // get image JSONObject 
    JSONObject objectInner = object.getJSONObject("image"); 
    // get thumbnailLink from objectInner 
    String strthumbnailLink= object.optString("thumbnailLink"); 
    WebImage objWebImage=new WebImage(strLink,strthumbnailLink); 

    // add objWebImage to ArrayList 
    webImages.add(objWebImage); 

} 
+0

乾杯隊友。 :)。 – Theo 2015-04-03 07:56:13