Challenge 1 Gson simpler solution


#1

This is another solution using JsonParser, TypeToken and @SerializedName("…").

  • JsonParser is used to get JsonElement which can be Object or Array and so on.
  • TypeToke is used to define List type.
  • @SerializedName is used for matching names in Serialized fields and Deserialized fields.

FlickrFetchr.java

public List<GalleryItem> fetchItems(){
     List<GalleryItem> items = new ArrayList<>();
    ...
String jsonString = getUrlString(url);
Log.i(TAG, "fetchItems: Received Json: " + jsonString);
// JSONObject jsonBody = new JSONObject(jsonString);
JsonParser parser = new JsonParser();
JsonElement photoJsonElement = parser.parse(jsonString)
                    .getAsJsonObject().get("photos")
                    .getAsJsonObject().get("photo");

Type listType = new TypeToken<ArrayList<GalleryItem>>(){}.getType();
Gson gson = new Gson();
items = gson.fromJson(photoJsonElement, listType);
//            parseItems(items, jsonBody);
 } catch (IOException ioe) {
            Log.e(TAG, "fetchItems: Failed to fetch items: ", ioe);
        }
   return items;
}

GalleryItem.java

  public class GalleryItem {
            @SerializedName("title")
            private String mCaption;
            @SerializedName("id")
            private String mId;
            @SerializedName("url_s")
            private String mUrl;
        ...
        }