A JSONArray object represent an ordered sequence of values. We use the put() method to add or replace values in the JSONArray object. The value can be of the following types: Boolean, JSONArray, JSONObject, Number, String or the JSONObject.NULL object.
Beside using the put() method we can also create and add data into JSONArray in the following ways:
- Using constructor to create
JSONArrayfrom string wrapped in square bracket[], where the values are separated by comma.JSONExceptionmaybe thrown if the string is not a valid JSON string. - Creating
JSONArrayby passing an array as an argument to its constructor, for example an array ofString[]. - Using constructor to create
JSONArrayfrom aCollection, such as anArrayListobject.
The following example show you how to create JSONArray object.
package org.kodejava.json;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class CreateJSONArray {
public static void main(String[] args) {
// Create JSONArray 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 wrapped in bracket and
// the values separated by comma. String value can be
// quoted with single quote.
JSONArray colorArray = new JSONArray("[1, 'Apple', 2022-02-07]");
System.out.println(colorArray);
// Create JSONArray from an array of String.
JSONArray stringArray =
new JSONArray(new String[]{"January", "February", "March"});
System.out.println(stringArray);
// Create JSONArray by passing a List to its constructor
List<String> list = new ArrayList<>();
list.add("Red");
list.add("Green");
list.add("Blue");
JSONArray listArray = new JSONArray(list);
System.out.println(listArray);
// Using for loop to get each value from the array
for (int i = 0; i < listArray.length(); i++) {
System.out.println("Color: " + listArray.get(i));
}
// Put JSONArray into a JSONObject.
JSONObject jsonObject = new JSONObject();
jsonObject.put("colors", listArray);
System.out.println(jsonObject);
}
}
Running the code above produces the following result:
["Java","Kotlin","Go"]
[1,"Apple","2022-02-07"]
["January","February","March"]
["Red","Green","Blue"]
Color: Red
Color: Green
Color: Blue
{"colors":["Red","Green","Blue"]}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
</dependencies>
