Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
Answer from Programmer Bruce on Stack Overflow
Top answer
1 of 6
102

Change

JSONObject objects = getArray.getJSONArray(i);

to

JSONObject objects = getArray.getJSONObject(i);

or to

JSONObject objects = getArray.optJSONObject(i);

depending on which JSON-to/from-Java library you're using. (It looks like getJSONObject will work for you.)

Then, to access the string elements in the "objects" JSONObject, get them out by element name.

String a = objects.get("A");

If you need the names of the elements in the JSONObject, you can use the static utility method JSONObject.getNames(JSONObject) to do so.

String[] elementNames = JSONObject.getNames(objects);

"Get the value for the first element and the value for the last element."

If "element" is referring to the component in the array, note that the first component is at index 0, and the last component is at index getArray.length() - 1.


I want to iterate though the objects in the array and get thier component and thier value. In my example the first object has 3 components, the scond has 5 and the third has 4 components. I want iterate though each of them and get thier component name and value.

The following code does exactly that.

import org.json.JSONArray;
import org.json.JSONObject;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    String jsonInput = "{\"JObjects\":{\"JArray1\":[{\"A\":\"a\",\"B\":\"b\",\"C\":\"c\"},{\"A\":\"a1\",\"B\":\"b2\",\"C\":\"c3\",\"D\":\"d4\",\"E\":\"e5\"},{\"A\":\"aa\",\"B\":\"bb\",\"C\":\"cc\",\"D\":\"dd\"}]}}";

    // "I want to iterate though the objects in the array..."
    JSONObject outerObject = new JSONObject(jsonInput);
    JSONObject innerObject = outerObject.getJSONObject("JObjects");
    JSONArray jsonArray = innerObject.getJSONArray("JArray1");
    for (int i = 0, size = jsonArray.length(); i < size; i++)
    {
      JSONObject objectInArray = jsonArray.getJSONObject(i);

      // "...and get thier component and thier value."
      String[] elementNames = JSONObject.getNames(objectInArray);
      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
      for (String elementName : elementNames)
      {
        String value = objectInArray.getString(elementName);
        System.out.printf("name=%s, value=%s\n", elementName, value);
      }
      System.out.println();
    }
  }
}
/*
OUTPUT:
3 ELEMENTS IN CURRENT OBJECT:
name=A, value=a
name=B, value=b
name=C, value=c

5 ELEMENTS IN CURRENT OBJECT:
name=D, value=d4
name=E, value=e5
name=A, value=a1
name=B, value=b2
name=C, value=c3

4 ELEMENTS IN CURRENT OBJECT:
name=D, value=dd
name=A, value=aa
name=B, value=bb
name=C, value=cc
*/
2 of 6
23
for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

🌐
Example Code
example-code.com › java › json_array_iterate.asp
Iterate over JSON Array containing JSON Objects | Chilkat Examples
import com.chilkatsoft.*; public class ChilkatExample { static { try { System.loadLibrary("chilkat"); } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); System.exit(1); } } public static void main(String argv[]) { boolean success = false; // Loads the following JSON array and iterates over the objects: // // [ // {"tagId":95,"tagDescription":"hola 1","isPublic":true}, // {"tagId":98,"tagDescription":"hola 1","isPublic":true}, // {"tagId":101,"tagDescription":"hola 1","isPublic":true}, // {"tagId":104,"tagDescription":"hola 1","isPublic":true}, /
🌐
Baeldung
baeldung.com › home › json › iterating over an instance of org.json.jsonobject
Iterating Over an Instance of org.json.JSONObject | Baeldung
May 5, 2025 - Traversing through a JSONObject is different from iterating through a JSONObject‘s key set. For this, we actually need to check the value type, too.
🌐
CodeSpeedy
codespeedy.com › home › how to iterate or loop through json array in java
How to iterate or loop through JSON array in Java - CodeSpeedy
March 7, 2022 - Here we already have a Detail.json file that contains an array of names. { "Names": [ "Aman", "Namita", "Piyush", "Priyansh", "kartik", "Adarsh" ] } import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class IterateJsonExample { public static void main(String[] args) { JSONParser jsonParserObj = new JSONParser(); try { JSONObject jsonObj = (JSONObject) jsonParserObj.
🌐
Javatpoint
javatpoint.com › iterate-json-array-java
Iterate JSON Array Java - Javatpoint
Iterate JSON Array Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Tpoint Tech
tpointtech.com › iterate-json-array-java
Iterate JSON Array Java - Tpoint Tech
May 7, 2025 - In order to read and write JSON data in Java, we use org.json library. The org.json library allow us to encode and decode JSON data in Java. The org.
🌐
CodingTechRoom
codingtechroom.com › question › iterate-jsonarray-java
How to Iterate Through a JSONArray in Java and Access its Elements - CodingTechRoom
Iterate through the JSONArray using a for loop, retrieving each JSONObject with the `getJSONObject` method. Access each property of the JSONObject by key and retrieve values appropriately.
🌐
Edureka Community
edureka.co › home › community › categories › java › iterate over a jsonobject
Iterate over a JSONObject | Edureka Community
June 27, 2018 - 7982/iterate-over-a-jsonobject · JSON library called JSONObject is used(I don't mind switching if I need to)
Find elsewhere
🌐
Quora
quora.com › How-do-I-iterate-through-JSON-array-object
How to iterate through JSON array object - Quora
Answer (1 of 2): I have the below code which is currently giving me one result. I would like to iterate through the “comments” so that end result will returns all the comments. for each(comments in r.orderLines){ // get Collection comments webservice = webServiceFactory.createWebService('
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-iterate-through-and-access-the-json-array-elements-using-rest-assured
How to iterate through and access the JSON array elements using Rest Assured?
November 17, 2021 - import static io.restassured.RestAssured.given; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; import io.restassured.response.Response; public class NewTest { @Test public void jsonIterateArr() { //base URI with Rest Assured class RestAssured.baseURI = "https://run.mocky.io/v3"; //obtain Response from GET request Response res = given() .when() .get("/8ec8f4f7-8e68-4f4b-ad18-4f0940d40bb7"); //convert JSON to string JsonPath j = new JsonPath(res.asString()); //get values of JSON array after getting array size int s = j.getInt("Location.size()"); for(int i = 0; i < s; i++) { String state = j.getString("Location["+i+"].State"); String zip = j.getString("Location["+i+"].zip"); System.out.println(state); System.out.println(zip); } } }
🌐
Rip Tutorial
riptutorial.com › json iteration
Java Language Tutorial => JSON Iteration
JSONArray arr = new JSONArray(); //Initialize an empty array //push (append) some values in: arr.put("Stack"); arr.put("Over"); arr.put("Flow"); for (int i = 0; i < arr.length(); i++) {//iterate over all values Object value = arr.get(i); //get ...
🌐
Webkul
webkul.com › home › how to iterate through jsonobject in java and kotlin
How to Iterate through JSONObject in Java and Kotlin - Webkul Blog
January 16, 2026 - JSON is essential for data exchange in modern applications using Java and Kotlin. In this Webkul guide, we explain simple and effective ways to iterate through JSON in both languages.
🌐
YouTube
youtube.com › watch
How to Iterate over JSON and Save to List in Java - YouTube
Learn how to effectively iterate through JSON arrays in Java and save the results into a list using ArrayList. This guide breaks down the process step by ste...
Published: October 12, 2025
Views: 0
🌐
Blogger
javarevisited.blogspot.com › 2022 › 12 › how-to-iterate-over-jsonobject-in-java.html
How to iterate over JSONObject in Java to print all key values? Example Tutorial
May 21, 2023 - In this article, I'll show you how you can print all keys and value from JSON message using JSONOjbect and Iterator. Once you parse your JSON String using JSONParser, you get a JSONObject, but its of no use if you want a POJO i.e. a plain old Java object.
🌐
YouTube
youtube.com › watch
How to Access JSON Array Values Using for-in Loop | JSON Tutorial - YouTube
In this tutorial, you will learn how to use a for-in loop to extract values from a JSON array. JSON arrays are collections of data stored in a specific forma...
Published: May 26, 2020