Search code examples
javaandroidapiflickr

JSONException: No value for photo


I'm using the Flickr API to get my app to display images depending on user search. I keep getting this error: JSONException: No value for photo

The call to get the photo:

public ArrayList<Category> processResults(Response response) {
    ArrayList<Category> categories = new ArrayList<>();

    try {
        String jsonData = response.body().string();
        if (response.isSuccessful()) {
            JSONObject flickrJSON = new JSONObject(jsonData);
            //json data
            JSONArray photoJSON = flickrJSON.getJSONArray("photo");
        }
    }
}

the json format is this:

{
    photos: { page: 1, 
              pages: 2165, 
              perpage: 100, 
              total: "216413", 
              photo: [ { id: "37095719122",
              ....
    }
}

Solution

  • Since the new JSONObject() part of your code works fine, its safe to assume that the JSON object you are getting is valid and in that case your actuall JSON object must look something like this :

    {
        photos: { page: 1, 
                  pages: 2165, 
                  perpage: 100, 
                  total: "216413", 
                  photo: [ { id: "37095719122",
                  .....
        }
    }
    

    The variable flickerJSON would contain this whole object and the only field it has is photos, while the photo field you are trying to access is an inner field of photos object.

    Hence, you can access the photo field like this :

    JSONArray photoJSON = flickrJSON.getJSONObject("photos").getJSONArray("photo");