我从Flickr api获得Json响应,如:
{
"photos": {
"page": 1,
"pages": 1,
"perpage": 100,
"total": 2,
"photo": [
{
"id": "14774811932",
"owner": "32738276@N08",
"secret": "cbb99f0039",
"server": "3853",
"farm": 4,
"title": "Weltschmerz",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0,
"date_faved": "1432471819"
},
{
"id": "13274800365",
"owner": "114920113@N07",
"secret": "b652859e6a",
"server": "3688",
"farm": 4,
"title": "cactus desert",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0,
"date_faved": "1432466782"
}
]
},
"stat": "ok"
}
我需要在ArrayList中获取两个Photo
对象。
我的代码是:
Helper helper = new Helper(this);
String jsonString = helper.loadJSONFromAsset();
Gson gson = new Gson();
Photos photos = gson.fromJson(jsonString,
new TypeToken<Photos>() { }.getType());
// ArrayList<Photo> photos = gson.fromJson(jsonString,
// new TypeToken<ArrayList<Photo>>(){}.getType());
目前我从资产加载文件。当这工作时,我将其更改为flickr api
照片课:
public class Photos {
Integer page;
Integer pages;
Integer perpage;
Integer total;
ArrayList<Photo> photos;
String stat;
//getters and setters here
我的理解是我首先提取photos
项,然后从该项中提取数组photo
,这样我就可以得到我需要的ArrayList。
答案 0 :(得分:1)
我认为你必须像这样创建Gson TypeToken:
public class Photos {
Integer page;
Integer pages;
Integer perpage;
Integer total;
ArrayList<Photo> photo;
String stat;
//setters and getters
}
通过这种方式,您可以复制Flickr JSON,Gson将正确映射Json:
Photos photos = gson.fromJson(jsonString,
new TypeToken<Photos>(){}.getType());
然后你可以用:
获取你的照片ArrayList photos.getPhoto();