Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Parsing JSON text

Write a method that pulls out information for each photo. Make a GalleryItem for each photo and add
it to a List.


Listing 25.12  Parsing Flickr photos (FlickrFetchr.java)


public class FlickrFetchr {


private static final String TAG = "FlickrFetchr";
...
public void fetchItems() {
...
}


private void parseItems(List items, JSONObject jsonBody)
throws IOException, JSONException {


JSONObject photosJsonObject = jsonBody.getJSONObject("photos");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("photo");


for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);


GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("id"));
item.setCaption(photoJsonObject.getString("title"));


if (!photoJsonObject.has("url_s")) {
continue;
}


item.setUrl(photoJsonObject.getString("url_s"));
items.add(item);
}
}
}


This code uses convenience methods such as getJSONObject(String name) and
getJSONArray(String name) to navigate the JSONObject hierarchy. (These methods are also
annotated in Figure 25.11.)


Flickr does not always return a url_s component for each image. You add a check here to ignore
images that do not have an image URL.

Free download pdf