Home > Java > javaTutorial > How can we write JSON object to file in Java?

How can we write JSON object to file in Java?

WBOY
Release: 2023-09-09 10:09:02
forward
698 people have browsed it

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

Example

import java.io.*;
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")) {
         file.write(obj.toJSONString());
         System.out.println("JSON Object write to a File successfully");
         System.out.println("JSON Object: " + obj);
      }
   }
}
Copy after login

course1.json file

How can we write JSON object to file in Java?

##Output

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

The above is the detailed content of How can we write JSON object to file in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template