gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:25:49 24 4
gpt4 key购买 nike

这是 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]

})
}

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

最佳答案

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

如果您需要一个保持顺序的 JavaScript 数据结构,您应该使用数组,而不是对象。返回一个排序的 List<City>从你的方法中,City有一个键和一个值。

关于java - 为什么 @ResponseBody 返回已排序的 LinkedHashMap 未排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com