How can I iterate a JSONArray of objects with a for each in JAVA?

2

I have the following JSONArray in java and I want to go through it with a foreach , I do not know if it is possible, thanks.

[{clave:valor,clave:valor,clave:valor},
 {clave:valor,clave:valor,clave:valor},
 {clave:valor,clave:valor,clave:valor},]
    
asked by Jesús Flor Farias 30.09.2016 в 21:20
source

2 answers

3

I guess it's this class

We can retrieve each object to see the values

JSONArray jsonArray = new JSONArray(jsonString);

for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject object = jsonArray.getJSONObject(i);
    clave = object.getString("clave");        
}
    
answered by 30.09.2016 в 21:26
0

You could do this:

  • Remove the array from the json object:

    JSONObject json = //Mi objeto json
    JSONArray jsonArray = (JSONArray) json.get("miObjeto"); 
    

    // assuming you have it defined within another json or

    JSONArray json = new JSONArray();
    
  • Iterate using forEach:

    jsonArray.stream()
        .forEach(s -> {
                //ejecutar acciones aquí
            }); 
    
  • answered by 19.01.2017 в 10:14