Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort/Arrange the JSON Object keys in android? [duplicate]

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...

like image 807
DarwinLouis Avatar asked Oct 26 '12 03:10

DarwinLouis


People also ask

How do I sort a JSON key?

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.

Does JSONObject maintain order?

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.

Can you sort JSON?

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 Answers

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.

like image 192
Archie.bpgc Avatar answered Oct 21 '22 09:10

Archie.bpgc