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

时间:2014-09-28 13:29:43

标签: 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]

        })
    }

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

2 个答案:

答案 0 :(得分:7)

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

如果您需要维护订单的JavaScript数据结构,则应使用数组,而不是对象。从您的方法中返回已排序的List<City>,其中City具有键和值。

答案 1 :(得分:0)

如果您想发送已排序的数据,请将您的对象的List或城市List<City>传递给已排序数据。

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

因此,最好使用List代替LinkedHashMap

JSON的大多数实现都不会保留对象name/value对的顺序,因为(by definition)不重要。