3

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have

                //access DB, returns a list of User objects, ordered
        ArrayList  users = MySQLDatabaseManager.selectUsers();
                //construct response
        JSONObject jsonResponse = new JSONObject();
        int key = 0;
        for(User user:users){
            log("Retrieve User " + user.toString());
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("name", user.getName());
            jsonObj.put("time", user.getTime());
            jsonResponse.put(key, jsonObj);
            key++;
        }
                //write out
        out.print(jsonResponse);

From the log I can see that the database returns User objects in the correct order.

At the front-end, I have

success: function(jsonObj){
            var json = JSON.parse(jsonObj);
            var id = 0;
            $.each(json,function(i,item) {              
                var time = item.time;               
                var name = item.name;               
                id++;
                $("table#usertable tr:last").after('<tr><td>' + id + '</td><td width="20%">' + time + 
                        '</td><td>' + name + 
                        '</td></tr>');
            });

        },

But the order is changed.

I only noticed this when the returned list has large size (over 130 users).

I have tried to debug using Firebug, the "response tab" in Firebug shows the order of the list is different with the log in the servlet.

Did i do anything wrong?

EDIT: Example

{"0":{"time":"2011-07-18 18:14:28","email":"xxx@gmail.com","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"xxx@gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":

,...,
"143":{"time":"2011-08-09 09:57:27","email":"xxx@gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}

,...,
"134":{"time":"2011-08-05 06:02:57","email":"xxx@gmail.com","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
user200340
  • 3,301
  • 13
  • 52
  • 74
  • Please give an example of what your JSON object looks like. JSON objects have no specific 'order' associated with them. For that purpose, you should use an Array (which itself, can be stored in a JSON object). – hayesgm Aug 09 '11 at 08:58
  • Hi ghayes, thanks for your hints (JSON objects have no specific 'order' associated with them). I was expecting that the returned objects has the same order as it was constructed. I had a closer look into the JSON objects from Firebug, and noticed that I can use the key value to re-order the list. – user200340 Aug 09 '11 at 09:13
  • If you are concerned about sorting, I also wrote some JavaScript into my answer to do just that. Enjoy! – hayesgm Aug 09 '11 at 09:24
  • possible duplicate of [JSONObject : Why JSONObject changing the order of attributes](http://stackoverflow.com/questions/17229418/jsonobject-why-jsonobject-changing-the-order-of-attributes) – Leo Jan 26 '14 at 13:20

3 Answers3

16

As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):

 jsonObj = 
          { items:
            [ { name: "Stack", time: "..." },
              { name: "Overflow", time: "..." },
              { name: "Rocks", time: "..." },
              ... ] };

This structure will ensure that your objects are inserted in the proper sequence.

Based on the JSON you have above, you could place the objects into an array and then sort the array.

 var myArray = [];
 var resultArray;

 for (var j in jsonObj) {
   myArray.push(j);
 }

 myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });

 for (var i = 0; i < myArray.length; i++) {
   resultArray.push(jsonObj[myArray[i]]);
 }

 //resultArray is now the elements in your jsonObj, properly sorted;

But maybe that's more complicated than you are looking for..

hayesgm
  • 8,678
  • 1
  • 38
  • 40
1

As mentioned by ghayes , json objects are unordered. There are multiple solutions to this problem.

  1. You can use array and the sort it to get the ordered list.
  2. You can use gson library to get the desired order of elements.

    I would prefer the second option as it is easy to use.
Community
  • 1
  • 1
Kanishk Gupta
  • 369
  • 2
  • 10
-1

As JSONObject is order less and internally uses Hashmap. One way to use it to download the all classes from org.json and use in your project directly by changing the internal HashMap implementation to LinkedHashMap in JSONObject.java file. below is the sorted json files https://github.com/abinash1/Sorted-Json-Object

abinash sahoo
  • 167
  • 1
  • 5