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
🌐
Coderanch
coderanch.com › t › 706235 › java › Identifying-JSONObject-JSONArray
Identifying JSONObject or JSONArray (Java in General forum at Coderanch)
Here are partial examples: This is the normal string that works: This is the response that causes the parser exception: ... Sam Ritter wrote:... is there a way to determine which sb is before running the parser? The easiest way is probably to use the parser to determine if JSON element is what you are expecting - as you have found, it will throw an exception if it is the wrong type of element.
Discussions

How to turn json objects into an array of json objects using Java?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
7
4
June 28, 2022
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
January 20, 2024
How to parse Json array with 2 or more different types using Jackson?

http://www.baeldung.com/jackson-inheritance

You'll need to have those types inherit from one base class though.

Also; that is really bad JSON.

More on reddit.com
🌐 r/javahelp
11
4
September 25, 2016
Jackson parsing JSON containing an array of objects and array of maps w/ dynamic keys
I believe Jackson will be able to deserialize this into a Map field... public class MyCustomClass { @JsonProperty("users") public LinkedHashMap users; @JsonProperty("jobs") public ArrayList jobs; } Depending on the configuration of your objectmapper, you probably don't even need the JsonProperty annotations More on reddit.com
🌐 r/androiddev
5
5
July 28, 2013
🌐
TutorialsPoint
tutorialspoint.com › how-to-read-parse-json-array-using-java
How to read/parse JSON array using Java?
The iterator() method of the JSONArray class returns an Iterator object, using which you can iterate through the contents of the current array. 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.
🌐
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 ).
🌐
TutorialsPoint
tutorialspoint.com › how-to-write-create-a-json-array-using-java
How to Write/create a JSON array using Java?
A JSON array is an ordered collection of values that are enclosed in square brackets i.e., it begins with '[' and ends with ']'. The values in the arrays are separated by ',' (comma).Sample JSON array{ "books": [ Java, JavaFX, Hbase, Cassandra, We
🌐
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
🌐
Android Developers
developer.android.com › api reference › jsonarray
JSONArray | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
Find elsewhere
🌐
Reddit
reddit.com › r/javahelp › how to turn json objects into an array of json objects using java?
r/javahelp on Reddit: How to turn json objects into an array of json objects using Java?
June 28, 2022 -

Hi. I'm new to java and stuck wondering how I would go about turning something like this: {} {} {} into this: [{},{},{}]. I'm trying to figure out how to do this to my incoming json data using Java. The data has like 20 similar objects, with the same keys but with constantly changing values.

Any help is much appreciated.

Sincerely,

your friendly neighborhood noob

Top answer
1 of 2
4
Look into Collections. you can use a List with List.of(obj1, obj2,...), The return here is going to be immutable and serializable, alternatively Arrays.asList({obj1, obj2,...}). Again, check out java.util.collections for more details
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Quora
quora.com › How-do-I-display-a-nested-array-JSON-object-in-Java-with-the-same-order-as-given-in-the-JSON-file
How to display a nested array JSON object in Java with the same order as given in the JSON file - Quora
Answer: I am assuming sample JSON Data to passe as below :- "{userInfo : [{username:user1}, {username:user2},{username:user3},{username:user4},{username:user5}]}" You need to add maven dependency :- org.json
🌐
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); } } }
🌐
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 - JSONObject obj1 = new JSONObject(); obj1.put("id", 1); obj1.put("name", "Alice"); JSONObject obj2 = new JSONObject(); obj2.put("id", 2); obj2.put("name", "Bob"); ... You can loop through data and dynamically put objects into the array.
🌐
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.
January 20, 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?

🌐
GitHub
github.com › stleary › JSON-java › blob › master › src › main › java › org › json › JSONArray.java
JSON-java/src/main/java/org/json/JSONArray.java at master · stleary/JSON-java
private void addAll(Collection<?> collection, boolean wrap, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { this.myArrayList.ensureCapacity(this.myArrayList.size() + collection.size()); ... private void ...
Author   stleary
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
If the value at the specified position is JsonValue.TRUE this method returns true. If the value at the specified position is JsonValue.FALSE this method returns false. Otherwise this method returns the specified default value. ... Returns true if the value at the specified location in this array is JsonValue.NULL.
🌐
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 - In this scenario, let’s consider a Java list named “articles” that contains elements as follows: public List<String> list = Arrays.asList("Article 1", "Article 2", "Article 3"); public String expectedJsonArray = "[\"Article 1\",\"Article ...
🌐
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 - Let's start with creating a JSON array in Java. Here, we will use some example data to input into the array, but you can use the data as per your requirements.
🌐
RestfulAPI
restfulapi.net › home › json › json array
JSON Array - Multi-dimensional Array in JSON
November 4, 2023 - The array index begins with 0. The square brackets [...] are used to declare JSON array.
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - Although we have a way to serialize a Java object to JSON string, there is no way to convert it back using this library. If we want that kind of flexibility, we can switch to other libraries such as Jackson. A JSONArray is an ordered collection of values, resembling Java’s native Vector implementation:
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-json-example
Java JSON Example | DigitalOcean
August 4, 2022 - javax.json.JsonReader: We can use this to read JSON object or an array to JsonObject.
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
NullPointerException - Thrown if the array parameter is null. public JSONArray(int initialCapacity) throws JSONException