5

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<String, Object>();
    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

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

My JSON is about 650.000 bytes. Does it also count as not large?
2

You're getting that error because JSONArray doesn't implement the Iterable interface.

In short, there's no clean way to solve this; you'd have to serialize the JSONObjects into your custom class.

To save you time though, using (Object one: all) over (i=0; i < all.getLength(); i++) won't give you any runtime improvements.

Just stick to the normal for loop.

Comments

-1

If you have very long arrays, don't iterate it that way. You can use gson to convert JSONArray to java array, like this:

static class Elem {    
   public String uname;
   public double uage;
}

...
JSONArray infojson = json.getJSONArray("getInfo");
String arrAsStr = infojson.toString();
Elem[] naviPoints = new Gson().fromJson(arrAsStr, Elem[].class);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.