JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).

To convert object to / from JSON, you should consider Jackson or Gson.

In this tutorial, we show you how to use JSON.simple to read and write JSON data from / to a file.

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"]

3. Read JSON from file

Use JSONParser to read above generated JSON file “test.json“, and display each of the values.

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class JsonSimpleExample {
     public static void main(String[] args) {
	JSONParser parser = new JSONParser();
	try {
		Object obj = parser.parse(new FileReader("c:\\test.json"));
		JSONObject jsonObject = (JSONObject) obj;
		String name = (String) jsonObject.get("name");
		long age = (Long) jsonObject.get("age");
		// loop array
		JSONArray msg = (JSONArray) jsonObject.get("messages");
		Iterator<String> iterator = msg.iterator();
		while (iterator.hasNext()) {
	} catch (FileNotFoundException e) {
	} catch (IOException e) {
	} catch (ParseException e) {


msg 1
msg 2
msg 3


  1. JSON.simple official website
  2. JSON.simple encoding JSON example
  3. JSON.simple decoding JSON example
Tags :
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website mkyong.com is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts