Kailash Dabhi Kailash Dabhi - 7 months ago 39
Android Question

Restore the order in which data is put into a JSONObject

i want to have json as it is inserted in this code but it works something different! i first want

and then
but this json gives the
first and then
. i have inserted the json as i want but why it gives different result please help me..

JSONObject json = new JSONObject();

try {
json.put("CustomerID", "069C21F1-EE87-4FB4-A129-478AEAA454FF");
json.put("Name", "Name_" + (int) Math.random() * 1000);
} catch (JSONException e) {
// TODO Auto-generated catch block


That is the expected behavior of a JSONObject. By its definition, it says:

An object as an unordered set of name/value pairs

however if you want it to be ordered do this:

1. prepare a LinkedHashMap object with elements

2. convert it to JSONObject


Map obj = new LinkedHashMap();
obj.put("a", "String1");
obj.put("b", new Integer(1));
obj.put("c", new Boolean(true));
obj.put("d", "String2");
JSONObject json = new JSONObject(obj);


download this library:


save all the files in a new package in your project

instead of using org.json.JSONObject use your.package.JSONObject which you added from the downloaded library.

now open JSONObject.java file and change HashMap() to LinkedHashMap() in the constructor

public JSONObject(Map map)