Convert 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"    ] ]
Updated on: 2020-02-19T07:46:28+05:30

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close