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
JSONArray
from string wrapped in square bracket[]
, where the values are separated by comma.JSONException
maybe thrown if the string is not a valid JSON string. - Creating
JSONArray
by passing an array as an argument to its constructor, for example an array ofString[]
. - Using constructor to create
JSONArray
from aCollection
, such as anArrayList
object.
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>
<!-- https://search.maven.org/remotecontent?filepath=org/json/json/20220924/json-20220924.jar -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
<type>bundle</type>
</dependency>
</dependencies>
Latest posts by Wayan (see all)
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023