java循环jsonarray,优化JSonArray for循环

博客内容讨论了在Android开发中尝试优化JSONArray的迭代过程,但遇到了因JSONArray不实现Iterable接口导致的错误。作者提供了两种编码方式,并指出尽管微观性能有所改善,但由于通常从Web服务返回的JSON数据不大,因此这种优化可能对应用性能影响有限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Today, I'm trying to optimize my JSONArray regarding android developer documentation. I was supposed to optimize it but there is error message coming out.

JSONArray infojson = json.getJSONArray("getInfo");

for(int i=0;i < infojson.length();i++){

JSONObject e = infojson.getJSONObject(i);

hm = new HashMap();

hm.put(MYNAME, e.getString("uname"));

hm.put(MYAGE, e.getString("uage"));

}

And I've optimized above coding as follow

JSONArray infojson = jsonObject.getJSONArray("getInfo");

for (Object o : infojson ) {

JSONObject jsonLineItem = (JSONObject) o;

String myname = jsonLineItem.getString("uname");

String myage = jsonLineItem.getString("uage");

}

Unfortunately, I got the following error message occuring on "infojson ) {"

Can only iterate over an array or an instance of java.lang.Iterable

解决方案

You can't use JSONArray with the that syntax as it doesn't implement Iterable interface. As a side note, the micro performance improvement you get probably won't affect your application performance as JSON results that are returned from the WebService are typically not large in size.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值