Using Retrofit to access JSON arrays
android, java, retrofit
Solution
A quick look at Retrofit's docs says it uses Gson to convert JSON to Java classes. This means you need a class hierarchy in Java that matches the JSON. Yours ... doesn't.
The returned JSON is an object with a single field "photos" that holds an object;
{ "photos" : { ... } }
So, your top level class would be a Java class with a single field:
public class PhotosResponse {
private Photos photos;
// getter/setter
}
And that `Photos` type would be another class that matches the JSON for the object that field contains:
{ "page":1, "pages":10, ... }
So you'd have:
public class Photos {
private int page;
private int pages;
private int perpage'
private int total;
private List<Photo> photo;
// getters / setters
}
And then you'd create a `Photo` class to match the structure of the object in that inner array. Gson will then map the returned JSON appropriately.
Problem
I thought I understood how to do this, but obviously not. I have my API from Flickr, which begins like so: ``` jsonFlickrApi({ "photos":{ "page":1, "pages":10, "perpage":100, "total":1000, "photo":[ { "id":"12567883725", "owner":"74574845@N05", "secret":"a7431762dd", "server":"7458", "farm":8, "title":"", "ispublic":1, "isfriend":0, "isfamily":0, "url_l":"http:\/\/farm8.staticflickr.com\/7458\/12567883725_a7431762dd_b.jpg", "height_l":"683", "width_l":"1024" } ``` Now the information I need to get is from within the photo array, so what I have been trying to do is: ``` interface ArtService { @GET("/services/rest/?method=flickr.photos.getRecent&extras=url_l&owner_name&format=json") PhotosResponse getPhotos(); public class PhotosResponse { Photos photos; } public class Photos { List<Arraz> photo; } public class Arraz { int id; String title; String owner; String url_l; } } ``` Very clear that I seem to be missing the point, however I am unsure of how to get the information..