How to Write/create a JSON array using Java?

JavaObject Oriented ProgrammingProgramming

A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma).

Sample JSON array

   "books": [ Java, JavaFX, Hbase, Cassandra, WebGL, JOGL]

The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program.

JSON-Simple maven dependency

Following is the maven dependency for the JSON-simple library −


Paste this with in the <dependencies> </dependencies> tag at the end of your pom.xml file. (before </project> tag)


To create an array in a JSON file using a Java program −

  • Instantiate the JSONObject class of the json-simple library.
//Creating a JSONObject object
JSONObject jsonObject = new JSONObject();
  • Insert the required key-value pairs using the put() method of the JSONObject class.
jsonObject.put("key", "value");
  • Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
JSONArray array = new JSONArray();
  • After adding all the required elements add the array into the JSON document using the put() method as −
  • Write the created JSON object into a file using the FileWriter class as −
FileWriter file = new FileWriter("E:/json_array_output.json");

Following Java program creates a JSON object with an array in it and writes it into a file named json_array_output.json.


import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class WritingJSONArray {
   public static void main(String args[]) {
      //Creating a JSONObject object
      JSONObject jsonObject = new JSONObject();
      //Inserting key-value pairs into the json object
      jsonObject.put("ID", "1");
      jsonObject.put("First_Name", "Krishna Kasyap");
      jsonObject.put("Last_Name", "Bhagavatula");
      jsonObject.put("Date_Of_Birth", "1989-09-26");
      jsonObject.put("Place_Of_Birth", "Vishakhapatnam");
      jsonObject.put("Country", "25000");
      //Creating a json array
      JSONArray array = new JSONArray();
      array.add("phone: 9848022338");
      array.add("city: Hyderabad");
      array.add("Area: Madapur");
      array.add("State: Telangana");
      //Adding array to the json object
      try {
         FileWriter file = new FileWriter("E:/json_array_output.json");
      } catch (IOException e) {
         // TODO Auto-generated catch block
      System.out.println("JSON file created: "+jsonObject);


JSON file created: {
"First_Name":"Krishna Kasyap",
"phone: 9848022338","city: Hyderabad",
"Area: Madapur",
"State: Telangana"],

If you observe the contents of the JSON file you can see the created data as −

Published on 03-Jul-2019 15:22:59