for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

Answer from Buhake Sindi on Stack Overflow
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonArray.html
JsonArray (Java(TM) EE 7 Specification APIs)
The values in a JsonArray can be of the following types: JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, and JsonValue.NULL. JsonArray provides various accessor methods to access the values in an array.
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-add-a-jsonarray-to-jsonobject-in-java
How can we add a JSONArray to JSONObject in Java?
July 4, 2020 - import org.json.*; import java.util.*; public class AddJSONArrayToJSONObjTest { public static void main(String args[]) { List<String> list = new ArrayList<String>(); list.add("Raja"); list.add("Jai"); list.add("Adithya"); JSONArray array = new JSONArray(); for(int i = 0; i < list.size(); i++) { array.put(list.get(i)); } JSONObject obj = new JSONObject(); try { obj.put("Employee Names:", array); } catch(JSONException e) { e.printStackTrace(); } System.out.println(obj.toString()); } } {"Employee Names:":["Raja","Jai","Adithya"]} raja ·
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
January 20, 2024
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
json - How to create correct JSONArray in Java using JSONObject - Stack Overflow
0 how to create json object with multiple array within it using org.json.JSONObject package in java? More on stackoverflow.com
🌐 stackoverflow.com
json - Accessing members of items in a JSONArray with Java - Stack Overflow
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array.. More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 3
58

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

2 of 3
1

You can prefer quick-json parser to meet your requirement...

quick-json parser is very straight forward, flexible, very fast and customizable. Try this out

[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -

  • Compliant with JSON specification (RFC4627)

  • High-Performance JSON parser

  • Supports Flexible/Configurable parsing approach

  • Configurable validation of key/value pairs of any JSON Heirarchy

  • Easy to use # Very Less foot print

  • Raises developer friendly and easy to trace exceptions

  • Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered

  • Validating and Non-Validating parser support

  • Support for two types of configuration (JSON/XML) for using quick-json validating parser

  • Require JDK 1.5 # No dependency on external libraries

  • Support for Json Generation through object serialization

  • Support for collection type selection during parsing process

For e.g.

JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
Arrays in JSON are almost the same as arrays in JavaScript.

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

Answer from Buhake Sindi on Stack Overflow
🌐
Coderanch
coderanch.com › t › 706235 › java › Identifying-JSONObject-JSONArray
Identifying JSONObject or JSONArray (Java in General forum at Coderanch)
Here is the code I use to create a JSONArray: This works fine unless the string (sb.toString()) turns out to be a JSONArray. I ultimately want an array but how do I tell which it is since the parser statement throws an exception saying a JSONArray cannnot be cast to a JSONObject?
Find elsewhere
🌐
JSON
json.org
JSON
Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language. ... A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array...
🌐
Baeldung
baeldung.com › home › json › jackson › convert json array to java list
Convert JSON Array to Java List | Baeldung
August 13, 2025 - Gson is a widely-used JSON library for serializing and deserializing Java objects to and from JSON. It offers a simple method to change a JSON array into a List object.
🌐
TutorialsPoint
tutorialspoint.com › how-to-write-create-a-json-array-using-java
How to Write/create a JSON array using Java?
Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
🌐
Baeldung
baeldung.com › home › json › introduction to json-java (org.json)
Introduction to JSON-Java | Baeldung
June 20, 2025 - Learn the fundamentals of parsing and manipulating JSON data with the JSON-Java library.
🌐
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 - Error: Can not deserialize instance of java.lang.Object[] out of START_OBJECT token at [Source: {"f1":1,"f2":"abc"}; line: 1, column: 1] ... import org.json.JSONObject; public class JSONParser { public static void main(String[] args) { String jsonStr = "{\"field1\":1,\"field2\":\"abc\"}"; JSONObject json = new JSONObject(jsonStr); Person person = new Person(); person.setKey(json.getInt("field1")); person.setValue(json.getString("field2")); System.out.println(person.toString()); } }
🌐
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?

🌐
Medium
medium.com › @Mohd_Aamir_17 › mastering-json-in-java-a-comprehensive-guide-to-handling-json-objects-arrays-and-nodes-with-df57bf0ebff1
Mastering JSON in Java: A Comprehensive Guide to Handling JSON Objects, Arrays, and Nodes with Jackson | by Mohd Aamir | Medium
November 4, 2024 - In essence, ArrayNode is suitable for structured JSON arrays, while JsonNode is ideal for complex, dynamic JSON processing. One of Jackson’s strongest features is its ability to easily convert JSON data into Java objects, and vice versa.
🌐
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
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
Append a boolean value. This increases the array's length by one. ... Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript | MDN
2 weeks ago - The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations.
🌐
Esri Developer
developers.arcgis.com › enterprise-sdk › api-reference › java › com › esri › arcgis › server › json › JSONArray.html
JSONArray (ArcObjects Java API)
This increases the array's length by one. ... value - An object value. The value should be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. ... Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then null elements will be added as necessary to pad it out. ... JSONException - If the index is negative. public JSONArray put(int index, java...
🌐
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.
🌐
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.