在通过 REST Api 发送之前,java 是否会操纵映射中键的顺序?

Does java manipulate the order of keys in map before sending via REST Api?

我有一个 LinkedHashMap,它有键(字符串)和值(某些对象的列表)对。在 return 语句之前,键的顺序是正确的。在 UI 结束时收到后,键的顺序似乎发生了变化。

java在这里有什么作用吗?如果是,如何纠正?我想要 UI 上的相同序列,这是从数据库中 return 编辑的。

即使您按顺序发送,JSON 对象也可能不保持属性的顺序。如果您需要有序的元素序列,请发送包含明确定义的对象的列表。

例如,而不是这个:

{
  "0": ["a0", "b0", "c0"],
  "1": ["a1", "b1", "c1"]
}

使用这样的东西:

[
  {
    "key": 0,
    "value": ["a0", "b0", "c0"]
  },
  {
    "key": 1,
    "value": ["a1", "b1", "c1"]
  }
]

LinkedHashMap

的文档

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Java中的LinkedHashMap将保持插入顺序。如果您从有序列表中读取键值对,并以相同的顺序将其插入到 LinkedHashMap 中,那么排列将被保留。

就是说,如果您是从 JSON 阅读本文,那么成对的顺序应视为无序

来自JSON规范RFC 8259

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

进一步:

JSON parsing libraries have been observed to differ as to whether or not they make the ordering of object members visible to calling software. Implementations whose behavior does not depend on member ordering will be interoperable in the sense that they will not be affected by these differences.

如果您需要解决方法,那么您可以按照 clayton.carmo 提供的答案进行操作。此解决方法的工作原理是将 JSON object 形式转换为 JSON array 键值对象。这保证保持排序。来自 RFC 文档:

An array is an ordered sequence of zero or more values.