为什么@ResponseBody将排序后的LinkedHashMap返回为未排序?
问题内容:
这是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]
})
}
Sorted
LinkedHashMap从getCityList方法返回为未排序的JSON对象。为什么在退货过程中更改订单?是否由于ResponseBody注释将LinkedHashMap转换为HashMap?我可以通过Gson库将已排序的对象转换为json字符串,并从我的getCityList方法返回json字符串,但我不喜欢这种解决方案。我该怎么做才能为JavaScript回调方法提供排序列表?
问题答案:
您期望JSON对象的条目与LinkedHashMap条目具有相同的顺序。那不会发生,因为JavaScript对象键没有固有顺序。它们就像Java
HashMaps。
如果需要维护顺序的JavaScript数据结构,则应使用数组而不是对象。List<City>
从您的方法返回一个排序,其中City
有一个键和一个值。