How to Write/create a JSON file using Java?

JavaObject Oriented ProgrammingProgramming

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. Sample JSON document

   "book": [
         "id": "01",
         "language": "Java",
         "edition": "third",
         "author": "Herbert Schildt"
         "id": "07",
         "language": "C++",
         "edition": "second",
         "author": "E.Balagurusamy"

Json-simple library

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 a JSON document 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");
  • Write the created JSON object into a file using the FileWriter class as −
FileWriter file = new FileWriter("E:/output.json");

Following Java program creates a JSON object and writes it into a file named output.json.


import org.json.simple.JSONObject;
public class CreatingJSONDocument {
   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", "Shikhar");
      jsonObject.put("Last_Name", "Dhawan");
      jsonObject.put("Date_Of_Birth", "1981-12-05");
      jsonObject.put("Place_Of_Birth", "Delhi");
      jsonObject.put("Country", "India");
      try {
         FileWriter file = new FileWriter("E:/output.json");
      } catch (IOException e) {
         // TODO Auto-generated catch block
      System.out.println("JSON file created: "+jsonObject);


JSON file created: {

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

Published on 03-Jul-2019 15:18:08