我根据某些搜索字词查询FlickR,响应是JSON数组。以下是根级别以及前两个结果:
{
photos: {
page: 1,
pages: 4222,
perpage: 100,
total: "422175",
photo: [
{
id: "28571356563",
owner: "8372889@N03",secret: "c4ca6c4364",
server: "8050",
farm: 9,
title: "95040021.jpg",
ispublic: 1,
isfriend: 0,
isfamily: 0,
url_m: "https://farm9.staticflickr.com/8050/28571356563_c4ca6c4364.jpg",
height_m: "332",
width_m: "500"
},
{
id: "28571342883",
owner: "96125450@N00",
secret: "db35a59412",
server: "8307",
farm: 9,
title: "Red #Sunset #Silhouette #Trees #Photography",
ispublic: 1,
isfriend: 0,
isfamily: 0,
url_m: "https://farm9.staticflickr.com/8307/28571342883_db35a59412.jpg",
height_m: "500",
width_m: "424"
},
当我加载结果时,我将遍历所有项目("总计"数字)并加载到RecyclerView中。
最终,我想要遍历"照片"然后得到" url_m"每张照片。这是我目前通过Retrofit调用FlickR API:
Call<List<Photo>> call = apiInterface.getImages(mQuery);
call.enqueue(new Callback<List<Photo>>() {
@Override
public void onResponse(Call<List<Photo>> call, Response<List<Photo>> response) {
}
@Override
public void onFailure(Call<List<Photo>> call, Throwable t) {
}
});
}
});
我如何遍历所有照片并获取每张照片的网址?我为每个完全映射到FlickR API JSON对象的模型类设置了:
答案 0 :(得分:1)
我认为您在代码中实施了错误的Retrofit回调。我可以看到你首先收到一个名为photos
的JSONObject,它包含一个JSONArray photo
,所以你的代码看起来应该是这样的
Call<PhotoResult> call = apiInterface.getImages(query);
call.enqueue(new Callback<PhotoResult>() {...}
如您所见,回调对象是PhotoResult
,它是json响应的根级别,在内部,您应该检索List<Photo>
集合。
要生成您的POJO,您可以使用本网站
http://www.jsonschema2pojo.org/
您的POJO应该是这样的
public class PhotoResult {
@SerializedName("photos")
@Expose
public Photos photos;
}
public class Photos {
@SerializedName("page")
@Expose
public Integer page;
@SerializedName("pages")
@Expose
public Integer pages;
@SerializedName("perpage")
@Expose
public Integer perpage;
@SerializedName("total")
@Expose
public String total;
@SerializedName("photo")
@Expose
public List<Photo> photo = new ArrayList<Photo>();
}
public class Photo {
...
}