2014-09-28 84 views
1

这里是控制器用SpringMVC代码段:为什么@ResponseBody将排序的LinkedHashMap返回为未排序?

@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对象。为什么在退货过程中订单被更改? 由于ResponseBody注释,LinkedHashMap是否转换为HashMap? 我可以通过Gson库将我的排序对象转换为json字符串,并从我的getCityList方法返回json字符串,但我不喜欢这个解决方案。我能做些什么来提供带有排序列表的JavaScript回调方法?

回答

4

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

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

+0

我不喜欢我的方法列表,因为我的jstl序列化使用LinkedHashMap:''。但我认为我不应该做异常,并在返回对ajax调用的响应的方法中将LinkedHashMap转换为List。 – yuceel 2014-09-28 16:14:27

0

如果你想发送排序数据,然后通过List你的对象或城市作为List<City>已排序的数据。

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

所以最好使用List而不是LinkedHashMap

JSON的大部分实现都不尽力保留对象的name/value对的顺序,因为它是(by definition)不重要。

+0

你确定关于LinkedHasMap的插入顺序吗? Java文档建议否则http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html – Shailendra 2014-09-28 14:41:44

+0

@Shailendra:请参阅http://java.dzone.com/articles/hashmap-vs-例如,treemap-vs#highlighter_525587。 – 2014-09-28 14:43:33

+0

JSON_的实现是什么意思? JSON是一种格式。 – zeroflagL 2014-09-28 14:45:35