7

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

Community
  • 1
  • 1
DarwinLouis
  • 1,111
  • 9
  • 15

2 Answers2

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

Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
0

You can't maintain the order of JSONObject response, because it is itself mentioned in the documents.

An object is an unordered set of name/value pairs.

I had faced the same problem and then i need to use either the gson library or to make json by ur logic..

An object is an unordered set of name/value pairs.

Best of luck.!

Kailash Dabhi
  • 3,473
  • 1
  • 29
  • 47