为什么 @ResponseBody 将排序的 LinkedHashMap 返回为未排序?

2023-12-03

这是 SpringMVC 控制器代码片段:

@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有一个键和一个值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 @ResponseBody 将排序的 LinkedHashMap 返回为未排序? 的相关文章

随机推荐