Search code examples
javaspringspring-bootspring-mvcpostman

Map as parameter in RestAPI Post request


I have created an API with a Map<String, Integer> parameter, like this:

@RequestMapping(value = "upload", method = RequestMethod.POST)
public ResponseEntity<String> handleContactsFileUpload(@RequestParam("file") MultipartFile file,
                                                       @RequestParam("name") String name,
                                                       @RequestParam("campaignAppItemId") Long campaignAppItemId,
                                                       @RequestParam("fileColumnHeaders") Map<String,Integer> fileColumnHeaders) throws Exception {
    if (file == null)
        return new ResponseEntity<>("No file uploaded", HttpStatus.BAD_REQUEST);
    contactService.handleContactsFile(file, name, campaignAppItemId,fileColumnHeaders);
    return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK);
}

I am trying to call this via Postman:

I passed the fileColumnHeaders inside Body->Form Data as in the screenshot.

Then I got a message like this in Postman:

Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found.

Anybody know why this message came ? How can we pass a map as a parameter in Rest API request? How can we pass a map through Postman?


Solution

  • You could use @RequestBody instead of @RequestParam for Maps and other non trivial data types and objects - this way spring will map the JSON representing your map parameter to a domain object, which is then serializable and can be converted to a java object.