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.