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


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

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),
                true,
                new char[] {'X', 'Y', 'Z'}
      };
      JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(objArray);
      System.out.println(jsonArray.toString(3)); //pretty print JSON
   }
}

Output

[
   "Array to JSON Array",
   10,
   30,
   14.26,
   true,
   [
      "X",
      "Y",
      "Z"
   ]
]
raja
Published on 05-Nov-2019 13:19:28
Advertisements