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

🌐
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 - Let’s try and keep a similar approach of using an iterator. Instead of calling keys(), though, we’ll call iterator(): void handleJSONArray(JSONArray jsonArray) { jsonArray.iterator().forEachRemaining(element -> { handleValue(element) }); }
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonarray
org.json.JSONArray.iterator java code examples | Tabnine
JSONObject jsonObject = (JSONObject) obj; JSONArray msg = (JSONArray) jsonObject.get("items"); Iterator iterator = msg.iterator(); while (iterator.hasNext()) { //System.out.println(iterator.next()); JSONObject item = (JSONObject) iterator.next(); ...
🌐
Example Code
example-code.com › java › json_array_iterate.asp
Java Iterate over JSON Array containing JSON Objects
Chilkat • HOME • Android™ • AutoIt • C • C# • C++ • Chilkat2-Python • CkPython • Classic ASP • DataFlex • Delphi DLL • Go • Java • Node.js • Objective-C • PHP Extension • Perl • PowerBuilder • PowerShell • PureBasic • Ruby • SQL Server • Swift • Tcl • Unicode C • Unicode C++ • VB.NET • VBScript • Visual Basic 6.0 • Visual FoxPro • Xojo Plugin
🌐
Java2s
java2s.com › example › java-api › org › json › simple › jsonarray › iterator-0-0.html
Example usage for org.json.simple JSONArray iterator
From source file:authorship.verification.ReadJSON.java · public static String readJson(String file) { JSONParser parser = new JSONParser(); try {//from ww w .ja v a 2s . co m FileReader fileReader = new FileReader(file); JSONObject json = (JSONObject) parser.parse(fileReader); language = (String) json.get("language"); //System.out.println("Language: " + language); JSONArray filenames = (JSONArray) json.get("problems"); Iterator i = filenames.iterator(); /*System.out.println("Filenames: "); while (i.hasNext()) { System.out.println(" " + i.next()); } */ } catch (Exception ex) { ex.printStackTrace(); } return language; }
🌐
Tabnine
tabnine.com › home page › code › java › com.google.gson.jsonarray
com.google.gson.JsonArray.iterator java code examples | Tabnine
JsonObject outputRecord = new JsonObject(); Iterator outputSchemaIterator = outputSchema.iterator();
🌐
Tabnine
tabnine.com › home page › code › java › org.json.simple.jsonarray
org.json.simple.JSONArray.iterator java code examples | Tabnine
try { JSONArray acls = (JSONArray) ((JSONObject) new JSONParser().parse(jsonAcl)).get("acls"); for (Iterator it = acls.iterator(); it.hasNext();) { JSONObject acl = (JSONObject) it.next(); String scheme = ((String) acl.get("scheme")).trim();
Find elsewhere
🌐
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 - Example NetBeans, etc. 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 = (JSO
🌐
Google Groups
groups.google.com › g › vertx › c › tTmv-US-HMI
Iterator on JsonArray issue
JsonArray array = new JsonArray(new String[] {"text1", "text2", "text3"}); and when I try to iterate through it: ... I get a java.lang.UnsupportedOperationException exception on remove() method. Am I doing anything wrong here?
🌐
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.
🌐
CodingTechRoom
codingtechroom.com › question › how-can-you-efficiently-iterate-through-a-jsonarray-in-java
How Can You Efficiently Iterate Through a JSONArray in Java? - CodingTechRoom
Use a for-each loop for cleaner ... elements appropriately when retrieving them: ```java Iterator<Object> iterator = jsonArray.iterator(); while (iterator.hasNext()) { Object element = iterator.next(); // process the element } ```...
🌐
CodePal
codepal.ai › code generator › iterating through a jsonarray using a for-each loop in java
Iterating through a JSONArray using a for-each loop in Java - CodePal
June 5, 2024 - In this example, we create a JSONArray object and add three elements to it: “Apple”, “Banana”, and “Orange”. We then pass this JSONArray to the iterateJSONArray method, which will iterate through the elements and print them.
🌐
Tpoint Tech
tpointtech.com › iterate-json-array-java
Iterate JSON Array Java - Tpoint Tech
May 7, 2025 - DoubleBuffer wrap() method in Java with Examples · javac is not Recognized · Image Processing in Java: Image Edge Detection Operators in Digital Image Processing · Dynamic Array in Java · Iterating Over Enum Values in Java · Shunting yard algorithm · Java Program to Determine Whether a Given String of Parentheses (Single Type) is Properly Nested ·