Here is some code using java 6 to get you started:

JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");

JSONArray ja = new JSONArray();
ja.put(jo);

JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder()
  .add("employees", Json.createArrayBuilder()
    .add(Json.createObjectBuilder()
      .add("firstName", "John")
      .add("lastName", "Doe")))
  .build();
Answer from Grammin on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object. The following example demonstrates how to create a JsonArray object from an input source using the method JsonReader.readArray():
Discussions

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
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
🌐
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 - Here is the correct example to parse your JSON. 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); } } }
🌐
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?

🌐
TutorialsPoint
tutorialspoint.com › how-to-write-create-a-json-array-using-java
How to Write/create a JSON array using Java?
JSONArray array = new JSONArray(); array.add("element_1"); array.add("element_2"); array.add("element_3"); After adding all the required elements add the array into the JSON document using the put() method as ? jsonObject.put("contact",array); Write the created JSON object into a file using ...
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
W3Schools.com
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-json-example
Java JSON Example | DigitalOcean
August 4, 2022 - Welcome to the Java JSON Example Tutorial. JSON (JavaScript Object Notation) is text-based lightweight technology for generating human readable formatted data. JSON represent object data in the form of key-value pairs.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-convert-json-array-to-string-array-in-java
How to Convert JSON Array to String Array in Java? - GeeksforGeeks
July 23, 2025 - // importing the packages import java.util.*; import org.json.*; public class GFG { public static void main(String[] args) { // Initialising a JSON example array JSONArray exampleArray = new JSONArray(); // Entering the data into the array ...
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - Here are the tokens received from the previous example: ... We’re provided with a CDL (Comma Delimited List) class to convert comma-delimited text into a JSONArray and vice versa.
🌐
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 - Here is a simple Java tutorial which demonstrate how to parse JSONObject and JSONArrays in Java. JSON syntax is a subset of the JavaScript object notation syntax: ... Just incase if you want to take a look at simple JSON tutorial which I’ve written sometime back. In this example we will read JSON File Crunchify_JSON.txt from file system and then we will iterate through it.
🌐
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.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
The internal form is an object ... values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. The constructor can convert a JSON text into a Java object....
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting a JSON Object to a JSON Array in Java - Java Code Geeks
August 1, 2025 - Let’s explore its usage through a practical example. // JsonConversionExample.java import org.json.JSONArray; import org.json.JSONObject; public class JsonConversionExample { public static void main(String[] args) { String jsonString = "{ \"apple\": 1, \"banana\": 2, \"cherry\": 3 }"; JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = new JSONArray(jsonObject.toMap().values()); System.out.println("Converted JSON Array:"); System.out.println(jsonArray.toString(2)); } }
🌐
Coderanch
coderanch.com › t › 694185 › open-source › reading-JSON-array
Help reading JSON array [Solved] (Open Source Projects forum at Coderanch)
May 15, 2018 - The following code reads the "Control" JSON element okay, but gets the following error when reading the Zones array element (the error occurs at the last code line):. Java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to and Zones and (Integer and (Integer ).
🌐
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.
🌐
Stack Exchange
sqa.stackexchange.com › questions › 47196 › how-to-create-correct-jsonarray-in-java-using-jsonobject
json - How to create correct JSONArray in Java using JSONObject - Software Quality Assurance & Testing Stack Exchange
March 30, 2021 - I'm trying to create a JSONArray but having difficulties cause the format I need to create is as follows: "header": [ { "name": "x", "id": "x", "boolean": "false", "data": { "x": { "a": "05", "b": "01" , "c": "246", "d": "Y" } } } ] java · json ...
🌐
TutorialsPoint
tutorialspoint.com › how-to-read-parse-json-array-using-java
How to read/parse JSON array using Java?
Iterator<String> iterator = jsonArray.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } Below is an example of a Java program that parses the above-created sample.json file, reads its contents, and displays them.
🌐
Baeldung
baeldung.com › home › java › java list › converting a java list to a json array
Converting a Java List to a Json Array | Baeldung
June 18, 2025 - @Test public void given_JavaList_whenUsingJacksonLibrary_thenOutJsonArray() throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String jsonArray = objectMapper.writeValueAsString(list); Assert.assertEquals(expectedJsonArray, jsonArray); }
🌐
Kodejava
kodejava.org › how-do-i-create-jsonarray-object
How do I create JSONArray object? - Learn Java by Examples
The following example show you ... and put some values JSONArray jsonArray = new JSONArray(); jsonArray.put("Java"); jsonArray.put("Kotlin"); jsonArray.put("Go"); System.out.println(jsonArray); // Create JSONArray from a string ...
🌐
Reddit
reddit.com › r/javahelp › using jsonarray, jsonobject etc. to parse json with java
r/javahelp on Reddit: using JSONArray, JSONObject etc. to parse JSON with Java
December 4, 2021 -

Hi,

I am reading json into a Java program, where I am attempting to process it. I'm having some challenges figuring out how to dig down into the data structure, in order to iterate through some of the deeper lists. 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 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.