javascript 有序 JSONObject

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6993645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:37:55  来源:igfitidea点击:

Ordered JSONObject

javascriptjqueryjsonservlets

提问by user200340

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

我有一个与数据库对话的 servlet,然后返回一个有序(按时间排序)对象的列表。在 servlet 部分,我有

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

我只在返回的列表很大(超过 130 个用户)时才注意到这一点。

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.

我尝试使用 Firebug 进行调试,Firebug 中的“响应选项卡”显示列表的顺序与 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"}}

回答by ghayes

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):

由于 JSON 对象本身没有顺序,因此您应该在 JSON 对象中使用数组来确保顺序。作为示例(基于您的代码):

 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.

根据上面的 JSON,您可以将对象放入数组中,然后对数组进行排序。

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

但也许这比你正在寻找的更复杂..

回答by Kanishk Gupta

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

正如ghayes所提到的,json 对象是无序的。这个问题有多种解决方案。

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

    I would prefer the second option as it is easy to use.
  1. 您可以使用数组并对其进行排序以获取有序列表。
  2. 您可以使用gson库来获取所需的元素顺序。

    我更喜欢第二种选择,因为它易于使用。

回答by abinash sahoo

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

由于 JSONObject 的顺序较少,并且在内部使用 Hashmap。一种使用它从 org.json 下载所有类并直接在您的项目中使用的方法,方法是将内部 HashMap 实现更改为 JSONObject.java 文件中的 LinkedHashMap。下面是排序的 json 文件 https://github.com/abinash1/Sorted-Json-Object