JSON.simple example to encode JSON data

JSON.simple is a simple lightweight API for encoding and decoding JSON data. It is flexible, simple and easy to use by reusing Map and List interfaces
It has no dependency on any third party libraries

This tutorial shows how to use JSON.simple to encode the following JSON data. Also shows how to write JSON data to file.

{
	"name": "Back to the Future",
	"year": 1985,
	"genres": ["Adventure", "Comedy", "Sci-Fi"],
	"techSpecs": {
		"Runtime": "116 min",
		"Color": true
	}
}

1) pom.xml

Add the following dependency to your pom.xml


    com.googlecode.json-simple
    json-simple
    1.1.1

2) Encode JSON data and write to file

Below example, encodes JSON data using JSONObject and JSONArray and writes it to a file named “movie-data.json”.

package com.kalliphant;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class JSONSimpleEncode {

	public static void main(String[] args) throws IOException {
		JSONObject movie = new JSONObject();

		movie.put("name", "Back to the Future");
		movie.put("year", new Integer(1985));

		JSONArray genres = new JSONArray();
		genres.add("Adventure");
		genres.add("Comedy");
		genres.add("Sci-Fi");
		movie.put("genres", genres);

		Map details = new HashMap();
		details.put("Runtime", "116 min");
		details.put("Color", true);
		movie.put("techSpecs", details);

		//Write to stdout
		System.out.println(movie.toJSONString());

		//Write to file
		FileWriter file = new FileWriter("movie-data.json");
		movie.writeJSONString(file);
		file.flush();
		file.close();

	}
}

3) Console Output

{"year":1985,"genres":["Adventure","Comedy","Sci-Fi"],
             "name":"Back to the Future",
             "techSpecs":{"Runtime":"116 min","Color":true}}

4) Creates a file named 'movie-data.json' with the below contents

{"year":1985,"genres":["Adventure","Comedy","Sci-Fi"],
 "name":"Back to the Future","techSpecs":{"Runtime":"116 min","Color":true}}

NOTE: If you see the above output, elements/keys are not in the same order as defined in JSON object. If you need a strict order of elements/keys see
Encode JSON data with strict order of keys example