Challenge 1 Gson simpler solution


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.

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)

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;

  public class GalleryItem {
            private String mCaption;
            private String mId;
            private String mUrl;