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
?
1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
We can also add a JSONArray to JSONObject. We need to add a few items to an ArrayList first and pass this list to the put() method of JSONArray class and finally add this array to JSONObject using the put() method.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With