0

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.

Sujay
  • 33
  • 6
  • 2
    *"The order of the map inside the entity is not maintained"* --- So what? The fields of a JSON object is **unordered**. From [json.org](https://www.json.org/json-en.html): *"An object is an **unordered** set of name/value pairs."* --- If your code requires them in a certain order, then your code is wrong. – Andreas Sep 07 '20 at 16:20
  • In JSON, "An object is an unordered set of name/value pairs". You can change your datastructures or as a hack (you shouldn't be doing this), you can read the request object as string and convert it to your object (gson) (maintain order of map with linked hash map). Refer answer : https://stackoverflow.com/questions/4515676/keep-the-order-of-the-json-keys-during-json-conversion-to-csv – Jerin D Joy Sep 07 '20 at 17:44

1 Answers1

0

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"}
  ]
}