Thursday, August 4, 2016

JSON Objects : Keeping the natural order

So JSON utilities doesn't guarantee the natural order of the field in an object when its converted to JSON object.
This usually should not be a problem in normal scenario as the order of the fields does not matter when we recreate the object.

But in case its required to pass the JSON object with the natural order of the fields we can make use of LinkedHashmap. Following example shows that how can we keep the natural order of fields in a JSON Object.

Code:

for(int i=0; i < 10; i++){

Map map = new LinkedHashMap(); // Use the LinkedHashMap
map.put("1", "test");
map.put("2", "test");
map.put("3", "test");
map.put("4", "test");
map.put("5", "test");
map.put("6", "test");
map.put("7", "test");
map.put("8", "test");
map.put("9", "true");
map.put("10", "jjjj");

System.out.println("JSON String : " + org.json.simple.JSONObject.toJSONString(map));

}

Output :

JSON String : {"1":"test","2":"test","3":"test","4":"test","5":"test","6":"test","7":"test","8":"test","9":"true","10":"jjjj"}