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 represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. 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.
๐ŸŒ
Stleary
stleary.github.io โ€บ JSON-java โ€บ org โ€บ json โ€บ JSONArray.html
JSONArray
A String value. ... 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.
Discussions

java - Convert string to JSON array - Stack Overflow
There seems to be a mistake in ... is created but not used. 2015-12-25T19:44:59.047Z+00:00 ... Just ignore the first line. It works with out it Gson gson = new Gson(); 2018-05-04T17:27:54.167Z+00:00 ... you will need to convert given string to JSONObject instead of JSONArray ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
how to create json array from java string for loop - Stack Overflow
@TedHopp its a multi valued string array, which i will get from the JCR, which is required to formulate as JSON ARRAY ... Okay. I reopened the question, as I thought it was about parsing. I see that @Kumaresan posted a workable solution. ... create a JSONArray like this. More on stackoverflow.com
๐ŸŒ stackoverflow.com
java - Create Json Array from array of strings - Stack Overflow
I did not notice that you added another string to 'jsonString' variable , I wanted to do the same but instead of getting along string with all the values I want to use array of string that the first item will be [path: root / ClientDate, val1: 1521560221877,val2:1519818708657, comp: false] ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 28, 2021
java - creating json string using JSONObject and JSONArray - Stack Overflow
Or if this is wrong way of creating JSON string, please suggest some better way with example of parsing in jQuery. ... I believe that you're organizing your data backwards. It seems that you want to use an array of NewsItems, and if so, then your java JSON generation code should look like this: More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 13, 2025
๐ŸŒ
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
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ how-to-write-create-a-json-array-using-java
How to Write/create a JSON array using Java?
September 6, 2023 - Following Java program creates a JSON object with an array in it and writes it into a file named json_array_output.json. import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WritingJSONArray { public static void main(String args[]) { //Creating a JSONObject object JSONObject jsonObject = new JSONObject(); //Inserting key-value pairs into the json object jsonObject.put("ID", "1"); jsonObject.put("First_Name", "Krishna Kasyap"); jsonObject.put("Last_Name", "Bhagavatula"); jsonObject.put("Date_Of_Birth", "1989-09-
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ java-how-to-create-json-arrays-420797
How to create JSON arrays | LabEx
Learn efficient Java techniques for creating and manipulating JSON arrays with practical examples and methods for modern software development
Find elsewhere
๐ŸŒ
Tabnine
tabnine.com โ€บ home page โ€บ code โ€บ java โ€บ org.json.jsonarray
org.json.JSONArray java code examples | Tabnine
DefaultHttpClient defaultClient = new DefaultHttpClient(); HttpGet httpGetRequest = new HttpGet(s); HttpResponse httpResponse = defaultClient.execute(httpGetRequest); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONObject jsonObject = new JSONObject(json); if (jsonObject.has("lessons")) { JSONArray jsonLessons = jsonObject.getJSONArray("lessons"); List<Lesson> lessons = new ArrayList<Lesson>(); for(int i = 0; i < jsonLessons.length(); i++) { JSONObject jsonLesson = jsonLessons.get(i); // Use optString instead of get on the next lines if you're not sure // the fields are always there String name = jsonLesson.getString("name"); String teacher = jsonLesson.getString("prof"); lessons.add(new Lesson(name, teacher)); } }
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ how-to-create-json-object-using-string
How to Create a JSON Object with JSON Array Using String in Java: Step-by-Step Example โ€” javathinking.com
Create a JSON string with a nested JSON array. Parse the JSON string into Java objects using org.json. Access, manipulate, and validate JSON data. Handle exceptions and use advanced libraries like Gson. Practice by modifying the JSON string (e.g., add a nested array of objects) and re-parsing it to reinforce your understanding!
๐ŸŒ
Javatpoint
javatpoint.com โ€บ json-array
JSON Array - javatpoint
JSON Array for beginners and professionals with examples of JSON with java, json array of string, json array of numbers, json array of booleans, json srray of objects, json multidimentional array. Learn JSON array example with object, array, schema, encode, decode, file, date etc.
๐ŸŒ
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 - The org.json.JSONObject is perhaps the most commonly used class for parsing a JSON boolean value in Java. Letโ€™s explore parsing different representations of boolean values. First, we create a JSONObject from a JSON string.
๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2013 โ€บ 04 โ€บ convert-json-array-to-string-array-list-java-from.html
How to Convert JSON array to String array in Java - GSon example
As I said earlier, there are lots of open-source libraries out there that can help to parse JSON data format and we have already seen Jackson library in our last example. In this tutorial, we will use GSON to parse the JSON data format and create a Java String array or List from JSON array representation.
๐ŸŒ
Processing
processing.github.io โ€บ processing-javadocs โ€บ core โ€บ processing โ€บ data โ€บ JSONArray.html
JSONArray
Append a boolean value. This increases the array's length by one. ... Put or replace a String value. If the index is greater than the length of the JSONArray, then null elements will be added as necessary to pad it out.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 49389162 โ€บ create-json-array-from-array-of-strings
java - Create Json Array from array of strings - Stack Overflow
March 28, 2021 - I did not notice that you added ... to use array of string that the first item will be [path: root / ClientDate, val1: 1521560221877,val2:1519818708657, comp: false] ......
๐ŸŒ
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 - Furthermore, web services and APIs often rely on JSON format to provide public data in a standardized manner. Its versatility makes it compatible with modern programming languages, allowing seamless integration across different platforms and technologies. 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 2\",\"Article 3\"]";
Top answer
1 of 4
22

I believe that you're organizing your data backwards. It seems that you want to use an array of NewsItems, and if so, then your java JSON generation code should look like this:

JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();

for(int i = 0 ; i< list.size() ; i++)
{
    p = list.get(i);

    obj.put("id", p.getId());
    obj.put("title", p.getTitle());
    obj.put("date". new MyDateFormatter().getStringFromDateDifference(p.getCreationDate()));
    obj.put("txt", getTrimmedText(p.getText()));

    arr.put(obj);

    obj = new JSONObject();
}

Now your JSON string will look something like this:

[{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
 {"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"},
 ...]

Assuming that your NewsItem gettors return Strings. The JSONObject method put is overloaded to take primitive types also, so if, e.g. your getId returns an int, then it will be added as a bare JSON int. I'll assume that JSONObject.put(String, Object) calls toString on the value, but I can't verify this.

Now in javascript, you can use such a string directly:

var arr =
    [{"id": "someId", "title": "someTitle", "date": "dateString", "txt": "someTxt"},
     {"id": "someOtherId", "title": "someOtherTitle", "date": "anotherDateString", "txt": "someOtherTxt"}];

for (i = 0; i < arr.length; i++)
    alert(arr[i].title); // should show you an alert box with each first title
2 of 4
1

The idea of the json object is the same as a dictionary/map where you have keys and values assigned to those keys, so what you want to construct would be something like this:

{"1": {"title": "my title", "date": "17-12-2011", "text": "HELLO!"}, "2": ....}

where the "1" is the id and the contents is another dictionary/map with the info.

lets say you assigned the object to a variable named my_map, now you will be able to handle it as:

 my_map.1.title
 my_map.3.text
 ...

to iterate over it just use:

for (info in my_map){
    data = my_map[info];
    //do what you need
}
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_json_arrays.asp
JSON Arrays
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null.
๐ŸŒ
Intellipaat
intellipaat.com โ€บ home โ€บ blog โ€บ how to create a correct jsonarray in java using jsonobject?
How to Create a Correct JSONArray in Java Using JSONObject?
May 27, 2025 - Learn how to create a correct JSONArray in Java using JSONObject. Understand how to set up the JSON library, handle nested structures, and format data properly