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

JavaJSONObject Oriented ProgrammingProgramming

The JSONArray is a sequence of values, the external text is a string enclosed in square brackets with commas separating the values and internal text is an object having get() and opt() methods, we need to access those values by index. The element() method for adding or replacing those values. An array is an object that stores multiple values of the same type. It can hold both primitive types and object references. We can convert a JSON array to array by using the toArray() method of JSONArray class. This method produces an Object[] with the contents of JSONArray.


public Object[] toArray()


import java.util.Arrays;
import net.sf.json.JSONArray;
public class ConvertJSONArrayToArrayTest {
   public static void main(String[] args) {
      JSONArray jsonArray = new JSONArray()
                                .element("Raja Ramesh")
                                .element("Tutorials Point")
                                .element(new String [] {"Java", "Testing", "Python"});
      String jsonStr = jsonArray.toString(3); //pretty print JSON
      System.out.println("JSON:\n" + jsonStr);
      Object[] array = jsonArray.toArray();
      System.out.println("Array:\n" + Arrays.toString(array));


   "Raja Ramesh",
   "Tutorials Point",
[Raja Ramesh, 115, Tutorials Point, Hyderabad, ["Java","Testing","Python"]]
Published on 11-Nov-2019 17:39:46