2014-09-28 222 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