How to encode JSON data with the strict order of elements/keys

This tutorial shows how to use JSON.simple to encode the following JSON data with the strict order of keys.
As per JSON RFC, an object is an unordered collection of zero or more name/value pairs and most implementations of JSON make no effort to preserve the order of an object's name/value pairs.
If order of the elements are important, it can be done using JSONValue.toJSONString(map) method as shown below

1) pom.xml

This examples uses JSON.simple library to encode the JSON data. 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 JSONValue and JSONArray and writes it to a file named “movie-data.json”.
It preserves the order of the elements

package com.kalliphant;

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

import org.json.simple.JSONArray;
import org.json.simple.JSONValue;

public class JSONSimpleEncodeOrdered {

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

		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 LinkedHashMap();
		details.put("Color", true);
		details.put("Runtime", "116 min");
		movie.put("techSpecs", details);

		// Write to stdout
		System.out.println(JSONValue.toJSONString(movie));
		
		// Write to file
		FileWriter file = new FileWriter("movie-data.json");
		JSONValue.writeJSONString(movie, file);
		file.flush();
		file.close();
	}
}


3) Console Output

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

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

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