JSON代码:http://headytunes.co/?json=1
我试图提取作者的名字,但只重复JSON列表中的第一个作者。我还试图从这个JSON中提取缩略图和多个类别,但我无法正确地提取图像或标记。
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Actors actor = new Actors();
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("posts");
JSONObject jsonoTwo =jsono.getJSONArray("posts").getJSONObject(0).getJSONObject("author");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
actor = new Actors();
actor.setName(object.getString("title"));
actor.setDescription(object.getString("excerpt"));
actor.setDate(object.getString("date"));
actor.setAuthor(jsonoTwo.getString("name"));
//.setTags(jsonoThree.getString("title"));
//actor.setImage(images.getString("url"));
songList.add(actor);
发布于 2014-08-13 02:06:42
我希望它没有任何错误:
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
actor = new Actors();
actor.setName(object.getString("title"));
actor.setDescription(object.getString("excerpt"));
actor.setDate(object.getString("date"));
actor.setAuthor(object.getString("name"));
JSONArray tags = object.getJSONArray("tag");
for (int j = 0; j < tags.length(); j++) {
// you can access each tag in this section
}
JSONArray attachment = object.getJSONArray("attachment");
for (int k = 0; k < tags.length(); k++) {
// you can access inside attachment
JSONObject insideAttachmentObj = attachment.getJSONObject(k);
insideAttachmentObj.getJSONObject("images").getJSONObject("thumbnail");
//or for accessing url :insideAttachmentObj.getJSONObject("images").getJSONObject("thumbnail").getString("url");
}
songList.add(actor);
发布于 2014-08-13 01:47:54
您只会反复获得第一个作者的名字,因为这就是您在代码中要做的。
你目前有:
jsono.getJSONArray("posts").getJSONObject(0).getJSONObject("author");JSONObject jsonoTwo =
。。
actor.setAuthor(jsonoTwo.getString("name"));
上面粗体部分是说,先获取第一篇文章的数据,然后再抓取作者。
更新您的代码,使其看起来如下:
actor.setAuthor(object.getJSONObject("author").getString("name"));
发布于 2014-08-13 02:18:54
您可以通过使用Gson从原始JSON创建模型类来简化整个过程。
要创建模型类,只需在返回的JSON中具有相同名称的属性,然后将JSON解析为如下模型的列表:
//Example model class
public Class Actor{
String name;
}
....
//Where you are parsing JSON
public void parseJSON(String json){
List<Actor> actors= Arrays.toList(new Gson().fromJson(json, Actor[].class));
//Use the actor object
}
https://stackoverflow.com/questions/25276742
复制相似问题