简体   繁体   中英

How to make sure order of map elements inside a @RequestBody of POST REST API is maintained?

The RequestBody entity Person in a POST request has a map as following

class Person {
    String name;
    int age;
    Map<String, String> otherProperties;
}

The above entity is mapped via RequestBody as following:

public void processInput(@RequestBody Person person) {

}

Though the invoker of this API sends following JSON in the input:

{
  "name": "nameOfPerson",
  "age": 10,
  "otherProperties": {
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
  }
}

the spring controller processes it as :

{
  "name": "nameOfPerson",
  "age": 10,
  "otherProperties": {
    "key2": "val2",
    "key3": "val3",
    "key1": "val1",
  }
}

The order of the map inside the entity is not maintained.

How to make sure the Spring controller reads and processes the map in the right order as was being sent by the invoker?

LinkedHashMap implementation or other implementation of Map does not guarantee that the input order be maintained.

You could create an object that contains your key and value, and then use a list instead of a map when passing the json object.

class Person {
    String name;
    int age;
    List<PersonProperty> otherProperties;
}
class PersonProperty {
    String name;
    String value;
}
{
  "name": "nameOfPerson",
  "age": 10,
  "otherProperties": [
    {"name":"key1", "value":"val1"},
    {"name":"key2", "value":"val2"},
    {"name":"key3", "value":"val3"}
  ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM