【问题标题】:Why @ResponseBody returns sorted LinkedHashMap as not sorted?为什么@ResponseBody 将已排序的 LinkedHashMap 返回为未排序?
【发布时间】:2014-11-22 23:41:48
【问题描述】:

这里是SpringMVC控制器代码sn-p:

@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回调方法?

【问题讨论】:

    标签: java json sorting spring-mvc linkedhashmap


    【解决方案1】:

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

    如果您需要一个维护顺序的 JavaScript 数据结构,您应该使用数组,而不是对象。从您的方法中返回一个已排序的List&lt;City&gt;,其中City 有一个键和一个值。

    【讨论】:

    • 我不喜欢 List 作为我的方法,因为我的 jstl 序列化使用 LinkedHashMap:&lt;form:options items="${cityList}"&gt;&lt;/form:options&gt;。但我不情愿地认为我应该例外,并在返回对 ajax 调用的响应的方法中将 LinkedHashMap 转换为 List。
    【解决方案2】:

    如果您想发送已排序的数据,请将您的对象或城市的 List 传递为已排序数据的 List&lt;City&gt;

    当我在我的应用程序中使用HashMap 时,我也遇到了同样的问题,它不能保证它会在same order in which we add them 中收到。我们必须通过它的密钥来访问它。

    所以最好使用List 而不是LinkedHashMap

    JSON 的大多数实现都不会努力保留对象的 name/value 对的顺序,因为它与 (by definition) 无关。

    【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2019-02-16
    • 2021-06-18
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多