yuc*_*eel 3 java sorting json 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;
}
Run Code Online (Sandbox Code Playgroud)
这是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]
})
}
Run Code Online (Sandbox Code Playgroud)
Sorted LinkedHashMap从getCityList方法返回未排序的JSON对象.为什么在退货过程中订单会发生变化 LinkedHashMap是否因为ResponseBody注释而转换为HashMap?我可以通过Gson库将我的排序对象转换为json字符串,并从我的getCityList方法返回json字符串,但我不喜欢这个解决方案.我该怎么做才能提供带有排序列表的javascript回调方法?
您期望JSON对象的条目与LinkedHashMap条目具有相同的顺序.这不会发生,因为JavaScript对象键没有内在的顺序.它们就像Java HashMaps.
如果您需要维护订单的JavaScript数据结构,则应使用数组,而不是对象.返回List<City>从您的方法中排序的,其中City包含键和值.
| 归档时间: |
|
| 查看次数: |
2999 次 |
| 最近记录: |