Why @ResponseBody returns sorted LinkedHashMap as not sorted?

后端 未结 2 679
野性不改
野性不改 2021-01-20 06:30

Here is SpringMVC Controller code snippet:

@RequestMapping(value = \"/getCityList\", method = RequestMethod.POST)
public @ResponseBody LinkedHashMap

        
相关标签:
2条回答
  • 2021-01-20 07:02

    You're expecting a JSON object's entries to have the same order as the LinkedHashMap entries. That won't happen, because JavaScript object keys have no intrinsic order. They're just like Java HashMaps.

    If you need a JavaScript data structure that maintains an order, you should use an array, not an object. Return a sorted List<City> from your method, where City has a key and a value.

    0 讨论(0)
  • 2021-01-20 07:14

    If you wanted to send sorted data then pass List of Your object or City as List<City> which have sorted data.

    I have also face same problem when I have used HashMap in my application, it doesn't guarantee that it will receive in same order in which we add them. We have to access it via it's key.

    so it's better to use List instead of LinkedHashMap.

    Most implementations of JSON make no effort to preserve the order of an object's name/value pairs, since it is (by definition) not significant.

    0 讨论(0)
提交回复
热议问题