Search code examples
javaspring-bootrestmodel-view-controller

How to send map(key-value pair) as request parameter in a GET call


Is it possible to send map as parameter in a GET call.? i searched and i could find for list and set collection. But did not find anything for map collection.

I tried the following, My controller method looks like this.

@GetMapping("/test")
    public ResponseEntity<?> mapTest(@RequestParam Map<String,String> params) {

        LOG.info("inside test with map  "+  params );

        return new ResponseEntity<String>("MAP", HttpStatus.OK);
    }

And i sent the following request from postman

http://localhost:8080/test?params={a:abc,b:bcd}

Everything works without errors and exceptions. But the map which i received looks like key=params , value={a:abc,b:bcd}

I expected the received map to be like key1="a" value1=abc ,key2="b" value2="bcd"


Solution

  • This is documented in the Spring MVC guide:

    When an @RequestParam annotation is declared as Map<String, String> or MultiValueMap<String, String> argument, the map is populated with all request parameters.

    This means that the response you currently get is the expected result. The Map contains a list of all parameters, and in your case, you only have a single parameter called param.

    If you need a custom parameter mapping, you'll have to implement it by yourself. Since you're not using JSON either, you probably have to manually parse the parameter.

    However, if your goal is to have a dynamic map of parameters, you can still use the Map<String, String>, but you'll have to change your request into:

    http://localhost:8080/test?a=abc&b=bcd