How to convert Java Array to JSON array?

By Saruque Ahamed Mollick

In this Java tutorial, you gonna learn how to convert Java Array to JSON array. In other programming languages, it is easy enough to work with JSON array and much easier. Because some languages are providing the inbuilt functions to work with JSON.

But fortunately, we are lucky enough that Google has provided a library named org.json.JSONArray

JSONArray()
This method Constructs an empty JSONArray.

Also read,

How to convert JSON array to normal Java Array Easily

How to remove null values from a String array in Java in various ways



Convert Java Array to JSON array with an example

In order to add this library to your project, you will need to create a maven dependency.

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

Again you are having a very useful method put()

Using this method you can add array elements into the JSONArray

Let’s take a look at this below example

import org.json.JSONArray;

public class MyClass {
   public static void main(String[] args) {
      String [] normal_array = {"CodeSpeedy", "JSON Array", "Java Array", "Saruque"};
      JSONArray json_array= new JSONArray();
      for (int i = 0; i < normal_array.length; i++) {
         json_array.put(normal_array[i]);
      }
      System.out.println(json_array);
   }
}

Output:

["CodeSpeedy","JSON Array","Java Array","Saruque"]

How to convert Byte Array to Image in java with easy example

If you want to convert Java ArrayList into JSON array then you may follow the below example:

import java.util.ArrayList;
import org.json.JSONArray;

public class MyClass {
   public static void main(String[] args) {
      ArrayList <String> my_arraylist= new ArrayList<String>();
      my_arraylist.add("CodeSpeedy");
      my_arraylist.add("JSON Array");
      my_arraylist.add("Java Array");
      my_arraylist.add("Saruque");
      JSONArray json_array = new JSONArray(arrayList);
      System.out.println(json_array);
   }
}

Output:

["CodeSpeedy","JSON Array","Java Array","Saruque"]

It is easier to work with ArrayList because you don’t need to use put() method in a for loop to add the array elements.

How to convert JSON array to normal Java Array Easily

How to convert BLOB to Byte Array in java

Leave a Reply

Your email address will not be published. Required fields are marked *