How to convert Java Array/Collection to JSON array?

Java 8Object Oriented ProgrammingProgramming

Google provides a library named org.json.JSONArray and, following is the maven dependency to add library to your project.

<dependency>
   <groupId>com.googlecode.json-simple</groupId>
   <artifactId>json-simple</artifactId>
   <version>1.1</version>
</dependency>

The JSONArray class of the org.json package provides put() method. Using this method, you can populate the JSONArray object with the contents of the elements.

Example

import org.json.JSONArray;
public class ArrayToJson {
   public static void main(String args[]) {
      String [] myArray = {"JavaFX", "HBase", "JOGL", "WebGL"};
      JSONArray jsArray = new JSONArray();
      for (int i = 0; i < myArray.length; i++) {
         jsArray.put(myArray[i]);
      }
      System.out.println(jsArray);
   }
}

Output

["JavaFX","HBase","JOGL","WebGL"]

In the same way you can pass a collection object to the constructor of the JSONArray class.

Example

import java.util.ArrayList;
import org.json.JSONArray;
public class ArrayToJson {
   public static void main(String args[]) {
      ArrayList <String> arrayList = new ArrayList<String>();
      arrayList.add("JavaFX");
      arrayList.add("HBase");
      arrayList.add("JOGL");
      arrayList.add("WebGL");
      JSONArray jsArray2 = new JSONArray(arrayList);
      System.out.println(jsArray2);
   }
}

Output

["JavaFX","HBase","JOGL","WebGL"]
raja
Published on 09-Jan-2018 17:59:16
Advertisements