我有一个与数据库通信的servlet然后返回一个有序(ORDER BY时间)对象的列表。在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);
从日志中我可以看到数据库以正确的顺序返回User对象。
在前端,我有
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>'); }); },
但订单改变了。
当返回的列表大小(超过130个用户)时,我才注意到这一点。
我尝试使用Firebug进行调试,Firebug中的“响应选项卡”显示列表的顺序与servlet中的日志不同。
我做错了什么吗?
编辑:示例
{"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"}}
由于JSON对象本身并不具有顺序,因此应在JSON对象中使用数组以确保顺序。作为示例(基于您的代码):
jsonObj =
{ items:
[ { name: "Stack", time: "..." },
{ name: "Overflow", time: "..." },
{ name: "Rocks", time: "..." },
... ] };
此结构将确保以正确的顺序插入对象。
基于上面的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;
但也许这比你想要的更复杂..
由于JSONObject的订单较少,因此内部使用Hashmap。一种方法是使用它从org.json下载所有类,并通过在JSONObject.java文件中将内部HashMap实现更改为LinkedHashMap直接在项目中使用。下面是排序的json文件https://github.com/abinash1/Sorted-Json-Object