简体   繁体   中英

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

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

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

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

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

}

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