1

I have this PostMapping method

@PostMapping("/offreStage/{id}/users")
public ResponseEntity<?> addAuthorizedStudents(@PathVariable Long id,
                                               @RequestBody Map<String, String> students) {
    return service.addAuthorizedStudentsToOffer(id, students);
}

and I use the following JSON payload to make my post request:

[
    {
        "value": 15,
        "label": "student2@gmail.com"
    },
    {
        "value": 14,
        "label": "student21@gmail.com"
    }
]

This returns the following:

"message": "JSON parse error: Cannot deserialize instance of java.util.LinkedHashMap out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.util.LinkedHashMap out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1]",

Eea Manco
  • 11
  • 1
  • 4

3 Answers3

1

The body sent does not match with the one in the function.

More precisely, this is your map :

  {
        "value": 15,
        "label": "student2@gmail.com"
  }

You need a list of map, so it won't work. So it should be this : List<Map<String, String>> in the function. Or better, use a collection (see this post).

RoadEx
  • 543
  • 2
  • 12
1

It doesn't work because of the way you are sending the JSON. In your example, you are essentially sending an Array of maps as Json and expecting Spring to convert it into a Map. In your JS convert the structure to a single map or you could use an object in your back end to map the data in the json accordingly like:

[
    {
        "value": 15,
        "label": "student2@gmail.com"
    },
    {
        "value": 14,
        "label": "student21@gmail.com"
    }
]

and then you could use your controller like :

@PostMapping("/offreStage/{id}/users")
public ResponseEntity<?> addAuthorizedStudents(@PathVariable Long id,
                                               @RequestBody List<ObjectClass> students) {
    return service.addAuthorizedStudentsToOffer(id, students);
}

and your object class could be like :

public class ObjectClass {
String value;
String label;
//getters and setters

}
Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39
0

Map is for key value pairs, you have list of key value pairs.

Change Map<String, String> to List<Map<String, String>>

Yuvaraj G
  • 1,157
  • 9
  • 17