最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ordered JSONObject - Stack Overflow

programmeradmin1浏览0评论

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":"[email protected]","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":

,...,
"143":{"time":"2011-08-09 09:57:27","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}

,...,
"134":{"time":"2011-08-05 06:02:57","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}

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":"[email protected]","origin":"origin-xxx","source":"xxx","target":"xxx","url":"xxx"},
"1":{"time":"2011-07-18 18:29:16","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"},
"2":

,...,
"143":{"time":"2011-08-09 09:57:27","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}

,...,
"134":{"time":"2011-08-05 06:02:57","email":"[email protected]","origin":"xxx","source":"xxx","target":"xxx","url":"xxx"}}
Share Improve this question edited Aug 9, 2011 at 9:15 user200340 asked Aug 9, 2011 at 8:54 user200340user200340 3,37113 gold badges55 silver badges77 bronze badges 4
  • 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 Commented Aug 9, 2011 at 8: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 Commented Aug 9, 2011 at 9:13
  • If you are concerned about sorting, I also wrote some JavaScript into my answer to do just that. Enjoy! – hayesgm Commented Aug 9, 2011 at 9:24
  • possible duplicate of JSONObject : Why JSONObject changing the order of attributes – Leo Commented Jan 26, 2014 at 13:20
Add a comment  | 

3 Answers 3

Reset to default 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..

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.

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

发布评论

评论列表(0)

  1. 暂无评论