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)
JsonArray provides various accessor methods to access the values in an array. The following example shows how to obtain the home phone number "212 555-1234" from the array built in the previous example: JsonObject home = array.getJsonObject(0); String number = home.getString("number");
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONArray.html
JSONArray
A JSONObject value. ... Get the long value associated with an index. ... JSONException - If the key is not found or if the value cannot be converted to a number. public String getString(int index) throws JSONException · Get the string associated with an index. ... A string value. ... JSONException - If there is no string value for the index. ... Determine if the value is null. ... Make a string from the contents of this JSONArray.
Discussions

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? 1 How to create JsonArray and JsonObject in JsonObject java More on stackoverflow.com
🌐 stackoverflow.com
java - Getting JSONObject from JSONArray - Stack Overflow
as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. More on stackoverflow.com
🌐 stackoverflow.com
java - How can I turn a JSONArray into a JSONObject? - Stack Overflow
And now I would like to turn that JSONArray into a JSONObject with the same information in it. So that I can pass around the Object and then when I want I can grab all the information out of the object. More on stackoverflow.com
🌐 stackoverflow.com
java - How to convert JSONObjects to JSONArray? - Stack Overflow
String resp = ...//String output from your source JSONObject ob = new JSONObject(resp); JSONArray arr = ob.getJSONArray("songs"); for(int i=0; i More on stackoverflow.com
🌐 stackoverflow.com
🌐
TutorialsPoint
tutorialspoint.com › how-can-we-add-a-jsonarray-within-jsonobject-in-java
How can we add a JSONArray within JSONObject in Java?
public JSONObject put(java.lang.String key, java.util.Collection<?> value) throws JSONException · import org.json.*; public class AddJSONArrayTest { public static void main(String[] args) throws JSONException { JSONArray array = new JSONArray(); array.put("INDIA"); array.put("AUSTRALIA"); array.put("ENGLAND"); JSONObject obj = new JSONObject(); obj.put("COUNTRIES", array); System.out.println(obj); } }
🌐
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()); } }
🌐
Coderanch
coderanch.com › t › 706235 › java › Identifying-JSONObject-JSONArray
Identifying JSONObject or JSONArray (Java in General forum at Coderanch)
I figured it out (I think). I used a try/catch on the parser then caught a ParserException and processed it as an JSONArray instead an JSONObject.
Find elsewhere
🌐
SourceForge
json-lib.sourceforge.net › apidocs › net › sf › json › JSONArray.html
JSONArray (Overview (json-lib jdk 1.3 API))
A JSONObject value. ... Get the long value associated with an index. ... JSONException - If the key is not found or if the value cannot be converted to a number. ... Get the string associated with an index. ... A string value. ... JSONException - If there is no value for the index. ... Returns true if this object is a JSONArray, false otherwise.
🌐
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" // } // ] JSONArray() getString()Gets the String value associated with an index ·
🌐
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
🌐
Baeldung
baeldung.com › home › json › get a value by key in a jsonarray
Get a Value by Key in a JSONArray | Baeldung
January 8, 2024 - A JSON message is usually comprised of JSON objects and arrays which may be nested inside one another. A JSONArray object is enclosed within square brackets [ ] whereas a JSONObject is enclosed within curly braces {}. For instance, let’s consider ...
🌐
IBM
ibm.com › support › pages › creating-json-string-json-object-and-json-arrays-automation-scripts
Creating a JSON String from JSON Object and JSON Arrays in Automation Scripts
# creating a JSON String with an array (directly executed via Run Automation Script button) from com.ibm.json.java import JSONObject, JSONArray from sys import * # method for creating a JSON formatted String including an array within def createJSONstring(): # defining the first child object ch1_obj = JSONObject() ch1_obj.put('CH_FIELD_1', 1) ch1_obj.put('CH_FIELD_2', 'VALUE_2') # defining the second child object ch2_obj = JSONObject() ch2_obj.put('CH_FIELD_1', 2) ch2_obj.put('CH_FIELD_2', 'VALUE_3') # adding child objects to children array ch_arr = JSONArray() ch_arr.add(ch1_obj) ch_arr.add(ch
🌐
Stleary
stleary.github.io › JSON-java › org › json › JSONObject.html
JSONObject
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get and opt methods for accessing the values by name, and ...
🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › json › JsonObject.html
JsonObject (Java(TM) EE 7 Specification APIs)
JsonWriter writer = ... JsonObject obj = ...; writer.writeObject(obj); JsonObject values can be JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, JsonValue.NULL.
🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonarray
org.json.JSONArray java code examples | Tabnine
Construct a JSONArray from a JSONTokener. ... Get the JSONObject associated with an index.
🌐
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
May 22, 2022 -

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.