Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach with JSONArray and JSONObject

Tags:

java

json

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?

like image 226
Jacobian Avatar asked Oct 19 '15 13:10

Jacobian


People also ask

How do I 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.

What is the difference between JSONArray and JSON object?

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.

Can we convert JSONArray to JSON object?

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.


1 Answers

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

like image 161
dguay Avatar answered Oct 08 '22 20:10

dguay