Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}
Answer from notnoop on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
javax.json · All Superinterfaces: Collection<JsonValue>, Iterable<JsonValue>, JsonStructure, JsonValue, List<JsonValue> public interface JsonArray extends JsonStructure, List<JsonValue> JsonArray represents an immutable JSON array (an ordered sequence of zero or more values).
Discussions

json - Accessing members of items in a JSONArray with Java - Stack Overflow
I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. More on stackoverflow.com
🌐 stackoverflow.com
New to Java, wanted some help with reading .json object arrays.
it gives me an error What's the error? More on reddit.com
🌐 r/javahelp
11
1
February 25, 2024
using JSONArray, JSONObject etc. to parse json with Java in Processing
Yeah that's because it's a JSONArray and not technically a Java array. You'll still need to use a function to get the individual objects in the array. See the docs JSONObject objectDataHash = objects.getJSONObject(i); JSONArray objectCoords = objectDataHash.getJSONArray("coordinates"); JSONArray coords0 = objectCoords.getJSONArray(0); //etc More on reddit.com
🌐 r/processing
2
2
January 29, 2022
using JSONArray, JSONObject etc. to parse JSON with Java
I'd highly advise you to use the ObjectMapper instead of JSONArray and JSONObject. Try to mimic the json objects structure with a class, create 0 field and all argument contrstructors, getters and setters and simply use new ObjectMapper().readValue(yourJsonString, YouMappedObject.class) More on reddit.com
🌐 r/javahelp
6
5
December 4, 2021
🌐
TutorialsPoint
tutorialspoint.com › how-to-write-create-a-json-array-using-java
How to Write/create a JSON array using Java?
To create an array in a JSON file using a Java program ? Instantiate the JSONObject class of the json-simple library. //Creating a JSONObject object JSONObject jsonObject = new JSONObject(); Insert the required key-value pairs using the put() method of the JSONObject class. jsonObject.put("key", ...
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - JSONObject – similar to Java’s native Map-like object, which stores unordered key-value pairs · JSONArray – an ordered sequence of values similar to Java’s native Vector implementation
🌐
Reddit
reddit.com › r/javahelp › new to java, wanted some help with reading .json object arrays.
r/javahelp on Reddit: New to Java, wanted some help with reading .json object arrays.
February 25, 2024 -
// Create a JSON object from the response
            JSONObject jsonResponse = new JSONObject(response.toString());

            // Write the JSON object to a file
            try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.json"))) {
                writer.write(jsonResponse.toString(4)); // The number specifies the indentation for pretty printing
            }

            System.out.println("JSON response written to output.json");
        } else {
            System.out.println("HTTP request failed with response code: " + responseCode);
        }
        // Read the JSON data from the file
        String jsonContent = new String(Files.readAllBytes(Paths.get("output.json")));

        // Create a JSONObject from the JSON data
        JSONObject jsonObject = new JSONObject(jsonContent);
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject skey = result.getJSONObject(5);
        String memo = skey.getString("memo");
        System.out.println("Value of 'key' in the JSON object: " + memo);
        // Close the connection
        connection.disconnect();

Code ^^

i am trying to read a specific sub-key of a .json array which is saved from an http GET request.
the structure of the .json file is something like this:

"jsonarray": [{
    "subkey1": "a"
    "subkey2": "b"
    "subkey3": "c"
    "subkey4": "d"
    "subkey5": "e"
    "subkey6": "f"
    "subkey7": "g"
}],
"key1": "h",
"key2": "i"

i want to read the value of subkey5 i.e. "e", but when i try to do it, it gives me an error. where am i going wrong?

Find elsewhere
🌐
Processing
processing.org › reference › jsonarray
JSONArray / Reference / Processing.org
String[] species = { "Capra hircus", "Panthera pardus", "Equus zebra" }; String[] names = { "Goat", "Leopard", "Zebra" }; JSONArray values; void setup() { values = new JSONArray(); for (int i = 0; i < species.length; i++) { JSONObject animal = new JSONObject(); animal.setInt("id", i); animal.setString("species", species[i]); animal.setString("name", names[i]); values.setJSONObject(i, animal); } saveJSONArray(values, "data/new.json"); } // Sketch saves the following to a file called "new.json": // [ // { // "id": 0, // "species": "Capra hircus", // "name": "Goat" // }, // { // "id": 1, // "species": "Panthera pardus", // "name": "Leopard" // }, // { // "id": 2, // "species": "Equus zebra", // "name": "Zebra" // } // ]
🌐
Open Liberty
openliberty.io › docs › modules › reference › 23.0.0.12 › com.ibm.websphere.appserver.api.json_1.0-javadoc › com › ibm › json › java › JSONArray.html
JSONArray (WebSphere JSON API)
com.ibm.json.java.JSONArray · All Implemented Interfaces: JSONArtifact, Serializable, Cloneable, Iterable, Collection, List, RandomAccess · public class JSONArray extends ArrayList implements JSONArtifact · Extension of ArrayList that only allows values which are JSON-able.
🌐
JanBask Training
janbasktraining.com › community › java › how-to-create-correct-jsonarray-in-java-using-jsonobject
How to create correct JSONArray in Java using JSONObject | JanBask Training Community
November 2, 2025 - To correctly create a JSONArray in Java using JSONObject, you need to follow a structured approach: first build each JSON object with key–value pairs, then add those objects into a JSONArray.
🌐
Oracle
docs.oracle.com › cd › F10042_01 › reference-java-api › oracle › adfmf › json › JSONArray.html
JSONArray (Oracle Fusion Middleware Java API Reference for Oracle Mobile Application Framework)
Oracle Fusion Middleware Java API Reference for Oracle Mobile Application Framework 2.5.1.0.0 E92592-01 ... A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get ...
🌐
ReqBin
reqbin.com › json › java › uzykkick › json-array-example
Java | What is JSON Array?
June 11, 2022 - Unlike dictionaries, where you can get the value by its key, in a JSON array, the array elements can only be accessed by their index. The following is an example of a JSON array with numbers. Below, you can find a list of JSON arrays with different data types. The Java code was automatically generated for the JSON Array example.
🌐
Javadoc.io
javadoc.io › static › org.json › json › 20171018 › index.html
JSON in Java 20171018 API
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting a JSON Object to a JSON Array in Java - Java Code Geeks
August 1, 2025 - To convert this object into a JSON array, the code first transforms the JSONObject into a Map using toMap(), then extracts only the values from that map using values(), and wraps those values in a new JSONArray. The result is an array containing just the values [1, 2, 3], discarding the original keys. Finally, the array is printed in a nicely formatted (indented) JSON string using toString(2). When this code is executed, it produces the following output in the IDE console: ... // JsonObjectToArrayExample.java import org.json.JSONArray; import org.json.JSONObject; public class JsonObjectToArray
🌐
Google Groups
groups.google.com › g › vertx › c › 5fgz-e2rTbk
casting a JsonArray to a specific type
JsonArray jarr = new JsonArray(messageAsyncResult.result().bodyAsString());
🌐
Crunchify
crunchify.com › json tutorials › how to parse jsonobject and jsonarrays in java? beginner’s guide
How to Parse JSONObject and JSONArrays in Java? Beginner's Guide • Crunchify
February 2, 2023 - Beginner's Guide * */ public class CrunchifyParseJsonObjectAndArray { public static void main(String[] args) { // JSON object string String jsonObjectString = "{\"name\":\"Crunchify\",\"year\":2023,\"city\":\"New York\"}"; // Parse the JSON object string into a JSONObject JSONObject jsonObject = new JSONObject(jsonObjectString); // Extract values from the JSON object String name = jsonObject.getString("name"); int year = jsonObject.getInt("year"); String city = jsonObject.getString("city"); // Print the values System.out.println("Name: " + name); System.out.println("Year: " + year); System.out
🌐
Reddit
reddit.com › r/processing › using jsonarray, jsonobject etc. to parse json with java in processing
r/processing on Reddit: using JSONArray, JSONObject etc. to parse json with Java in Processing
January 29, 2022 -

Hi,

I am reading json into a Java program in Processing. I'm attaching below excerpts of the Java, and the toy/test json.

Here is the toy/test json:

{
    "objects": [
        {
            "type": "object-1",
            "coordinates": [
                [
                    0,
                    5
                ],
                [
                    5,
                    10
                ],
                [
                    10,
                    15
                ],
                [
                    15,
                    0
                ]
            ]
        }
    ]
}

What I WANT to do is grab the list of objects associated with the key "objects", and then iterate through the dictionaries that compose the list, further extracting components (coordinates, say, if the type is what i'm after).

The thing is, I don't know how to do this. The code below is an attempt, but it doesn't work.

Here's the Java excerpt:

JSONObject json;

void setup() {
  
  size(800, 494);
  
  // input json file
  String inputJsonFile = "input.json";
  String inputJsonFileContentsString = "";
  
  try { 
      inputJsonFileContentsString = readFileIntoString( inputJsonFile );
  }
  catch (IOException e) {
      e.printStackTrace();
  }
  
  //JSON parser object to parse read file
  JSONObject inputJsonData = parseJSONObject( inputJsonFileContentsString );
  
  // recover list of objects
  JSONArray objects = inputJsonData.getJSONArray( "objects" );
  
  // print json data: iterate over list of objects, retrieving type and coordinates
  int arrayLength = objects.size();
  for ( int i = 0; i < arrayLength; i++ ) {

    // THIS DOESN'T WORK
    // I want the next dictionary/hash, but how to retrieve it?
    JSONObject objectDataHash = objects[ i ];
    
  }
  
}

Thank you. I'm normally work with Python, it's been a while since I've done a lot of coding in Java so I'm probably missing something obvious. Thank you.

🌐
Cloudera Community
community.cloudera.com › t5 › Support-Questions › Converting-JSON-to-Java-Object-Array › m-p › 153155
Solved: Converting JSON to Java Object Array - Cloudera Community - 153155
February 1, 2017 - import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JSONParser { public static void main(String[] args) throws IOException { try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("Server1.json"), "UTF-8")){ Gson gson = new GsonBuilder().create(); Person p = gson.fromJson(reader, Person.class); System.out.println(p); } } }