0

I am trying to loop through an array of photo objects in java, from the flickr api but cant seem to target the photo array because it is nested within a json object with page values as seen below.

{
    "page" : 1,
    "pages" : 10,
    "perpage" : 100,
    "total" : 1000,
    "photo" : [
        {photo objects}
    ]
}

I expect to get photo objects which i can then pass to a photos model class.

  • Do you use an available JSON parser, or are you parsing it by hand? – QBrute Jun 26 '19 at 08:58
  • Possible duplicate of [How can I access and process nested objects, arrays or JSON?](https://stackoverflow.com/questions/11922383/how-can-i-access-and-process-nested-objects-arrays-or-json) – Vimukthi Jun 26 '19 at 09:00
  • @Vimukthi_R Thank you for researching duplicate question which may answer this question as well. But the question you found here isn't actually a suitable duplicate target, because the linked question is for Javascript, not Java like this one here. – Tom Jun 26 '19 at 09:42
  • Can you print the data that you receive? And add on the question. – c-an Jun 27 '19 at 01:31

3 Answers3

0

I dont know what library you are using, i personally use GSON and am going to base the example on that library.

this is how i would go about it:

if(json.has("photo"){
    JsonArray photoArray = json.get("photo").getAsJsonArray(); //get the full array
    for(int i = 0; i < photoArray.size(); i++){ //loop through all photo objects inside the array
        PhotoObject photoObject = photoArray.get(i);
        //do something with your objects
    }
}
Alan
  • 949
  • 8
  • 26
0

Hey you can try something like this:

//make the string into a JSONObject
JSONObject obj = new JSONObject("ur Json string"); 

//get the JSONArray from the object
JSONArray array1 = obj.getJSONArray("photo"); 

array1 is your JSON array. To get the JSON object, you can:

JSONObject photo1 = array1.getJSONObject(0); //get first element in the JSONArray

Then you can do mapping to map the JSONObject to your own Photo object.

Refer to:

JSONObject - https://developer.android.com/reference/org/json/JSONObject.html

JSONArray - https://developer.android.com/reference/org/json/JSONArray.html

Wilson Sim
  • 513
  • 1
  • 5
  • 15
0

You can use two classes for this,

page values class

class Response {
    private int page;
    private int pages;
    private int perpage;
    private int total;
    private List<Photo> photo; //List of photo objects

    //getters setters
}

photo class

class Photo {
    private int id;
    private String name;

    //getters setters
}

In your main class you can access photo objects using below code,

for (Photo p : response.getPhoto()) {
    System.out.println(p.id);
}
Vimukthi
  • 846
  • 6
  • 19