下面存储在arraylist ArrayListlatestNews;
中的JSONObject格式字符串response.toString()是
{
"blue": [
{
"title": "http:\\www.b"
},
{
"info": " http:\\www.b"
},
{
"link": "http:\\www.b"
},
{
"image": "http:\\www.b"
},
{
"pubDate": "http:\\www.b"
},
{
"guid": "http:\\www.b"
}
]
}{
"blue": [
{
"title": "http"
},
{
"info": " 5449 1616"
},
{
"link": "http:\\www.b"
},
{
"image": "http:\\www.b"
},
{
"pubDate": "Thu, 26 Jun 2014 16:25:25 GMT"
},
{
"guid": "http:\\www.b"
},
{
"title": "Weekend"
},
{
"info": " 3345 4353"
},
{
"link": "http:\\www.b.."
},
{
"image": "http:\\www.b..."
},
{
"pubDate": "Mon, 23 Jun 2014 09:47:25 GMT"
},
{
"guid": "http:\\www.b"
}
]
}{
"blue": [
{
"title": "KARAVAN "
},
{
"info": " 4444444"
},
{
"link": "http:\\www...."
},
{
"image": "http:\\www...."
},
{
"pubDate": "Thu, 26 Jun 2014 16:25:25 GMT"
},
{
"guid": "http:\\www...."
},
{
"title": "IMC "
},
{
"info": " 134 3333"
},
{
"link": "http:\\www...."
},
{
"image": "http:\\www...."
},
{
"pubDate": "Mon, 23 Jun 2014 09:47:25 GMT"
},
{
"guid": "http:\\www...."
},
{
"title": "property "
},
{
"info": " 633 1352 \ 537 18211"
},
{
"link": "http:\\www....l"
},
{
"image": "http:\\www...."
},
{
"pubDate": "Thu, 26 Jun 2014 16:09:01 GMT"
},
{
"guid": "http:\\www...."
}
....
LatestNews.class
public class LatestNews {
public String title;
public String info;
public String link;
public String image;
public String pubDate;
public String guid;
public LatestNews (String title_,String info_,String link_,String image_,String pubDate_,String guid_){
this.title=title_;
this.info=info_;
this.link=link_;
this.image=image_;
this.pubDate=pubDate_;
this.guid=guid_;
}
}
我按如下方式提取json
JSONObject obj = new JSONObject(response.toString());
JSONArray venues = obj.getJSONArray("blue");
System.out.println("response object "+venues.length());
for (int x=0;x<venues.length();x++){
JSONObject keyValue = venues.getJSONObject(x);
if (keyValue.has("title")){
System.out.println("xxxtitle "+keyValue.getString("title"));
}
}
但是当我打印keyValue.getString(“title”)时,只打印第一个标题。如何在将每个蓝色对象保存到arraylist之前打印所有元素。欢迎任何帮助。
答案 0 :(得分:1)
首先,大多数情况下,您的JSON响应不符合标准和优化的响应。
实现您的Web服务逻辑以获得以下格式的响应,它将帮助您减少解析逻辑/代码和迭代,这将有助于您提高应用程序性能。
{
"blue": [
{
"title": "http:\\www.b",
"info": " http:\\www.b",
"link": "http:\\www.b",
"image": "http:\\www.b",
"pubDate": "http:\\www.b",
"guid": "http:\\www.b"
},
{
"title": "http:\\www.b",
"info": " http:\\www.b",
"link": "http:\\www.b",
"image": "http:\\www.b",
"pubDate": "http:\\www.b",
"guid": "http:\\www.b"
}
]
}
现在关于JSON解析教程/代码,网上和Stackoverflow上都有大量示例,请点击此处:JSON Parsing in Android
您的代码和JSON格式/逻辑中的错误:
正如你所说,只有第一个标题被打印出来,原因就是你写了obj.getJSONArray("blue");
,它只会给你第一个'蓝色'对象,所以它会给你一个蓝色对象的标题值。
我已经在上面建议了一个优化的解决方案!