Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON pretty-print without changing the order

Tags:

java

json

gson

I use json-simple and want to have pretty-print for debugging purposes.

Here is a very relavant SO question: Pretty-Print JSON in Java

However the answer in the given thread, not only fixes the indentation but also changes the order of the items to [a ... z] using the string order of the keys.

Is there any way to fix the indentation without changing the order of the items in my JSONObject?

Example:

JSONObject myJSon = new JSONObject();
myJSon.put("zzz", 1);
myJSon.put("aaa", 1);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println( gson.toJson(myJSon) );

Output:

{
  "aaa": 1,
  "zzz": 1
}

Desired output:

{
  "zzz": 1,
  "aaa": 1
}

Edit: I'm using: org.json.simple.JSONObject

like image 865
Sait Avatar asked Jul 22 '13 22:07

Sait


People also ask

How do I make JSON data look pretty?

If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first: var jsonString = '{"some":"json"}'; var jsonPretty = JSON. stringify(JSON. parse(jsonString),null,2);

Does JSONObject maintain order?

The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter.


1 Answers

org.json.simple.JSONObject class extends java.util.HashMap and this is the reason why you see this order of the properties on output. setPrettyPrinting() method doesn't change the order. You can remove it from source code and nothing change. If you want to keep the order you can use java.util.LinkedHashMap instead of org.json.simple.JSONObject.

Simple example:

import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonProgram {

    public static void main(String[] args) throws Exception {
        Map<String, Integer> myJSon = new LinkedHashMap<String, Integer>();
        myJSon.put("zzz", 1);
        myJSon.put("aaa", 1);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println(gson.toJson(myJSon));
    }
}
like image 149
Michał Ziober Avatar answered Oct 12 '22 11:10

Michał Ziober