How to convert an array to JSON Array using JSON-lib API in Java?n

A Java array is an object which stores multiple variables of the same type, it can hold primitive types and object references whereas JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values, an internal form is an object having get() and opt() methods for accessing the values by index and element() method for adding or replacing values. In the first step, we can create an Object[] array and pass this parameter as an argument to the toJSON() of JSONSerializer class and typecasting it to get the JSON array.

We can convert Object[] array to JSONArray in the below example


import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class ConvertArrayToJSONArrayTest {
   public static void main(String[] args) {
      Object[] objArray = new Object[] {
               "Array to JSON Array",
                new Integer(10),
                new Long(30),
                new Double(14.26),
                new char[] {'X', 'Y', 'Z'}
      JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(objArray);
      System.out.println(jsonArray.toString(3)); //pretty print JSON


   "Array to JSON Array",