How can we write JSON objects to a file in Java?

The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to write JSON files and it can be used to encode or decode JSON text and fully compliant with JSON specification(RFC4627). In order to read a JSON file, we need to download the json-simple.jar file and set the path to execute it.


import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONObjectWriterToFileTest {
   public static void main(String[] args) throws IOException {
      JSONObject obj = new JSONObject();
      obj.put("Name", "Adithya");
      obj.put("Course", "MCA");
      JSONArray subjects = new JSONArray();
      subjects.add("Subject1: DBMS");
      subjects.add("Subject2: JAVA");
      subjects.add("Subject3: PYTHON");
      obj.put("Subjects:", subjects);
      try (FileWriter file = new FileWriter("/Users/User/Desktop/course1.json")) {
         System.out.println("JSON Object write to a File successfully");
         System.out.println("JSON Object: " + obj);

course1.json file


JSON Object write to a File successfully
JSON Object: {"Subjects:":["Subject1: DBMS","Subject2: JAVA","Subject3: PYTHON"],"Course":"MCA","Name":"Adithya"}