Kailash Dabhi Kailash Dabhi - 5 months ago 33
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

CustomerID
and then
Name
but this json gives the
Name
first and then
CustomerID
. 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
e.printStackTrace();
}

Answer

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

Example:

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);

EDIT:

download this library:

https://github.com/douglascrockford/JSON-java

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)
Comments