Possible Duplicate:
Sort JavaScript object by key
I am creating JSONArray from JSONObject in android. The JSONArray that i wanted to be is: [{"last_name":"cruz", "first_name":"juan", "middle_name":"sam"}]
but it appears [{"first_name":"cruz", "last_name":"juan", "middle_name":"sam"}]
how can I arrange the array in order that I wanted?
Thanks...
Enter your JSON into the first text area, or drag and drop a file, after, select the sort method you're going to use, key value requires the key name (if not specified selects the first key), click the example button to get an idea on how it works. The result will automatically sort and display in the output text area.
As seen above in the JSONResponse, since object is an unordered set of name/value pairts, so JSONObject isn't preserving the order of my object's name/value pairs.
You cannot sort a JSON string.. JSON is an Object Notation for data transport - ie, a string. You will have to evaluate it as an object literal (e.g. with eval) and make any changes you want before reserializing it.
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);
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)
This will make the JSONObject store data in the order you entered the values using put.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With