Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

java - Foreach with JSONArray and JSONObject

I'm using org.json.simple.JSONArray and org.json.simple.JSONObject. I know that these two classes JSONArray and JSONObject are incompatible, but still I want to do quite a natural thing - I want to for-each over JSONArray parsing at each iteration step one JSONObject (nested inside that JSONArray). I try to do it like so:

JSONArray arr = ...; // <-- got by some procedure
for(JSONObject o: arr){
    parse(o);
}

When I try to compile this code, indeed I get "incompatible types" error, even though it looks so natural. So, my question is what is the best way to iterate through JSONArray?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seems like you can't iterate through JSONArray with a for each. You can loop through your JSONArray like this:

for (int i=0; i < arr.length(); i++) {
    arr.getJSONObject(i);
}

Source


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...