Code Robo
Formatter
Comparator
Tester
Merger
Converter
Utility
Java Code Complience
Validator
EncoderDecoder
Virtual Service
How to maintain the order of the keys in a JSONObject
       Talk to EasyAssistant

JSONObject is an unordered collection of name/value pairs.It does not maintain the insertion order of the keys. Now Question is how to maintain the insertion order of keys an a JSONObject.


There is no direct way make the JSONObject orderable. But there are multiple hooks that can be used to acheive target goal (maintaing order in JSONObject).
If you want to maintain the original order in the JSONObject same as the input JSON String, you can adopt any one of the hooks mentioned in this page.
If you are using org.json.simple.JSONObject of Simple-JSON libarty, there is no hook to maintain the insertion order in the keys of JSON Object as org.json.simple.JSONObject class extends HashMap class (which does not maintain any order). So if you are using org.json.simple.JSONObject, change to org.json.JSONObject object of gson library. Both org.json.simple.JSONObject and org.json.simple.JSONObject work in similar fashion so moving from org.json.simple.JSONObject to org.json.simple.JSONObject is easily doable.
if you are using org.json.JSONObject, there are multiple hooks which can be used to maintain order in the keys on JSONObject.


Example 1: org.json.simple.JSONObject uses HashMap object as instance varible (varibale name is 'map'), Through reflection we can assign a LinkedHashmap object on the map variable, we can acheive our targeted goal.
Sample Java Code:
 
private JSONObject sortAJsonObject(org.json.JSONObject jsonObject) throws Exception {

		Iterator keySetIterator = jsonObject.keys();
		Map map = new TreeMap();
		while (keySetIterator.hasNext()) {
			Object key = keySetIterator.next();
			Object value = jsonObject.get("" + key);
			map.put(key.toString(), value);
		}

		Set keySet = map.keySet();
		for (Object key : keySet) {
			jsonObject.remove("" + key);
		}

		Field filedMap = jsonObject.getClass().getDeclaredField("map");
		filedMap.setAccessible(true);// as map is a private variable
		filedMap.set(jsonObject, new LinkedHashMap<>());
		filedMap.setAccessible(false);
		// Add all keys
		for (Object key : keySet) {
			Object value = map.get(key);
			jsonObject.put("" + key, value);
		}
		return jsonObject;
	}



Example 2: You can use com.google.gson.Gson and com.google.gson.JsonObject class to convert a json string to JsonObject. it maintains the order of the key present in input JSON String.
Sample Java Code:
private static void tm() {
		String str = "";
		str = str + " {\n";
		str = str + "    \"bpay\": 0,\n";
		str = str + "    \"wallet\": 0,\n";
		str = str + "    \"cash\": 0,\n";
		str = str + "    \"client_name\": \"DDR 1\"\n";
		str = str + "  }\n";
		com.google.gson.Gson gson = new Gson();
		com.google.gson.JsonObject jsonObject = gson.fromJson(str, JsonObject.class);
		System.out.println("jsonObject=" + jsonObject);
	}


Example 3: Get the JSONObject.java file. Change the map variable. Assign a LinkedHashMap object to the map variable and to class Change from HashMap() to LinkedHashMap()
This is not a very good option. This option is not recomended.
public JSONObject() {
        this.map = new LinkedHashMap();
    }



Post Your Comment:
Name :
Email ( Optional) :
Comments / Suggestion (* Required) It is required: :
: