In this tutorial, we will convert a Java list into a JSON Object. Most of the times, the JSONs built in the organizations are complex. It contains string, int, list, arrays and soon.
In this tutorial, we will use the below mentioned dependency.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230618</version>
</dependency>
Let us create a Java List.
List<String> list = Arrays.asList("Test 1", "Test 2", "Test 3", "Test 4");
We want to convert this list in a JSON Object.
Below is the sample code.
import org.json.JSONArray;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
public class ListToJsonObject {
@Test
public static void test() {
List<String> list = Arrays.asList("Test 1", "Test 2", "Test 3", "Test 4");
System.out.println("List :" + list);
JSONArray jsonArray = new JSONArray(list);
System.out.println("Json Array :" + jsonArray);
}
}
The output of the above program is

In the above code snippet, we create an instance of the JSONArray class, passing the Test List as a parameter.