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.

Syntax

public Object[] toArray()

Example

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("115")
                                .element("Tutorials Point")
                                .element("Hyderabad")
                                .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("-------------------------------------------------------------------");
      System.out.println("Array:\n" + Arrays.toString(array));
   }
}

Output

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