java - 为什么 @ResponseBody 返回已排序的 LinkedHashMap 未排序?

标签 java json sorting spring-mvc linkedhashmap

这是 SpringMVC Controller 代码片段:

@RequestMapping(value = "/getCityList", method = RequestMethod.POST)
public @ResponseBody LinkedHashMap<String, String> getCityList(@RequestParam(value = "countryCode") String countryCode, HttpServletRequest request) throws Exception {
    //gets ordered city list of country  [sorted by city name]
    LinkedHashMap<String, String> cityList = uiOperationsService.getCityList(countryCode); 

    for (String s : cityList.values()) {
        System.out.println(s); //prints sorted list  [sorted by name]
    }
    return cityList;
}

这是ajax调用:

function fillCityList(countryCode) {
        $.ajax({
            type: "POST",
            url: '/getCityList',
            data: {countryCode:countryCode},
            beforeSend:function(){
                $('#city').html("<option value=''>-- SELECT --</option>" );
            }
        }).done(function (data) {

            console.log(data); // UNSORTED JSON STRING  [Actually sorted by key... not by city name]

        })
    }

已排序的 LinkedHashMap 从 getCityList 方法返回未排序的 JSON 对象。为什么在返回过程中更改订单? LinkedHashMap是不是因为ResponseBody注解才转为HashMap? 我可以通过 Gson 库将我排序的对象转换为 json 字符串,并从我的 getCityList 方法返回 json 字符串,但我不喜欢这个解决方案。我该怎么做才能为排序列表提供 javascript 回调方法?

最佳答案

您希望 JSON 对象的条目与 LinkedHashMap 条目具有相同的顺序。这不会发生,因为 JavaScript 对象键没有内在顺序。它们就像 Java HashMap。

如果您需要一个保持顺序的 JavaScript 数据结构,您应该使用数组,而不是对象。返回一个排序的 List<City>从你的方法中,City有一个键和一个值。

关于java - 为什么 @ResponseBody 返回已排序的 LinkedHashMap 未排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085353/

相关文章:

JavaFX - 中心文件选择器弹出窗口

java - 为什么我收到 "Is already defined in package unnamed package"错误?

javascript - 尝试将数据推送到 JSON 数组

html - 将 JSON 链接到 html 以使用 particles.js 不起作用

javascript - Web 服务器提供 HTML 页面而不是 JSON

list - 如何对包含异步的函数返回的值使用 List.sort?

java - 这个排序顺序有名字吗?

java - 为什么 Eclipse JFace 的 Window 类创建一个调整大小监听器然后立即将其删除?

java - 没有 arg 构造函数或 arg 构造函数

python - pandas多索引直接排序