Eea Manco
Eea Manco

Reputation: 11

Spring Boot REST to read JSON array payload

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": "[email protected]"
    },
    {
        "value": 14,
        "label": "[email protected]"
    }
]

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

Upvotes: 1

Views: 3550

Answers (3)

Ananthapadmanabhan
Ananthapadmanabhan

Reputation: 6226

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": "[email protected]"
    },
    {
        "value": 14,
        "label": "[email protected]"
    }
]

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

}

Upvotes: 1

RoadEx
RoadEx

Reputation: 541

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

More precisely, this is your map :

  {
        "value": 15,
        "label": "[email protected]"
  }

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).

Upvotes: 1

Yuvaraj G
Yuvaraj G

Reputation: 1237

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

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

Upvotes: 0

Related Questions