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


The net.sf.json.JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values and 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. The values can be any of these types like Boolean, JSONArray, JSONObject, Number, String and JSONNull object.

We can convert a collection(List) to JSON array in the below example

Example

import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
public class ConvertCollectionToJsonArrayTest {
   public static void main(String[] args) {
      List<String> strList = Arrays.asList("India", "Australia", "England", "South Africa");
      JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(strList);
      System.out.println(jsonArray.toString(3)); //pretty print JSON
      List<Object> objList = new ArrayList<Object>();
      objList.add("List Data");
      objList.add(new Integer(50));
      objList.add(new Long(99));
      objList.add(new Double(50.65));
      objList.add(true);
      objList.add(new char[] {'X', 'Y', 'Z'});
      jsonArray = (JSONArray)JSONSerializer.toJSON(objList);
      System.out.println(jsonArray.toString(3)); //pretty print JSON
   }
}

Output

[
   "India",
   "Australia",
   "England",
   "South Africa"
]
[
   "List Data",
   50,
   99,
   50.65,
   true,
      [
      "X",
      "Y",
      "Z"
   ]
]

Updated on: 08-Jul-2020

587 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements