This controller
@GetMapping("temp")
public String temp(@RequestParam(value = "foo") int foo,
@RequestParam(value = "bar") Map<String, String> bar) {
return "Hello";
}
Produces the following error:
{
"exception": "org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException",
"message": "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"
}
What I want is to pass some JSON with bar
parameter:
http://localhost:8089/temp?foo=7&bar=%7B%22a%22%3A%22b%22%7D, where foo
is 7
and bar
is {"a":"b"}
Why is Spring not able to do this simple conversion? Note that it works if the map is used as a @RequestBody
of a POST
request.
Here is the solution that worked:
Just define a custom converter from String
to Map
as a @Component
. Then it will be registered automatically:
@Component
public class StringToMapConverter implements Converter<String, Map<String, String>> {
@Override
public Map<String, Object> convert(String source) {
try {
return new ObjectMapper().readValue(source, new TypeReference<Map<String, String>>() {});
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}