How do I create JSONArray object?

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 of String[].
  • Using constructor to create JSONArray from a Collection, such as an ArrayList 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();

        // 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]");

        // Create JSONArray from an array of String.
        JSONArray stringArray =
                new JSONArray(new String[]{"January", "February", "March"});

        // Create JSONArray by passing a List to its constructor
        List<String> list = new ArrayList<>();
        JSONArray listArray = new JSONArray(list);

        // 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);

Running the code above produces the following result:

Color: Red
Color: Green
Color: Blue

Maven Dependencies

    <!-- -->

Maven Central

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.