How to create correct JSONArray in Java using JSONObject

To create a JSON array using JSONObject in Java, you can use the put() method of the JSONObject class to add elements to the array.

Here is an example of how you can create a JSON array containing two elements using JSONObject:

import org.json.JSONArray;
import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        
        JSONObject obj1 = new JSONObject();
        obj1.put("key1", "value1");
        obj1.put("key2", "value2");
        
        JSONObject obj2 = new JSONObject();
        obj2.put("key3", "value3");
        obj2.put("key4", "value4");
        
        array.put(obj1);
        array.put(obj2);
        
        System.out.println(array.toString());
    }
}

This will output the following JSON array:

[{"key1":"value1","key2":"value2"},{"key3":"value3","key4":"value4"}]

You can also use the put() method to add primitive values to the JSON array, like this:

import org.json.JSONArray;

public class Main {
    public static void main(String[] args) {
        JSONArray array = new JSONArray();
        
        array.put(1);
        array.put(2);
        array.put(3);
        
        System.out.println(array.toString());
    }
}

This will output the following JSON array:

[1,2,3]