JSON.simple example – Write JSON

1. JSON.simple Dependency

JSON.simple is available at Maven central repository, just declares following dependency in your pom.xml file.


2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.

import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JsonSimpleExample {
public static void main(String[] args) {

JSONObject obj = new JSONObject();
obj.put(“name”, “mkyong.com”);
obj.put(“age”, new Integer(100));

JSONArray list = new JSONArray();
list.add(“msg 1”);
list.add(“msg 2”);
list.add(“msg 3”);

obj.put(“messages”, list);

try {

FileWriter file = new FileWriter(“c:\\test.json”);

} catch (IOException e) {

Output – See content of file named “test.json“.

“messages”:[“msg 1″,”msg 2″,”msg 3”]