Arc*_*hie 1 spring http-request-parameters spring-boot spring-restcontroller
这个控制器
@GetMapping("temp")
public String temp(@RequestParam(value = "foo") int foo,
@RequestParam(value = "bar") Map<String, String> bar) {
return "Hello";
}
Run Code Online (Sandbox Code Playgroud)
产生以下错误:
{
"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"
}
Run Code Online (Sandbox Code Playgroud)
我要的是通过一些JSON与bar参数:
HTTP://本地主机:8089 / TEMP富= 7&酒吧=%7B%22A%22%3A%22B%22%7D? ,哪里foo是7和bar是{"a":"b"}
为什么春节不能够这个简单的转换吗?请注意,如果将地图用作请求中@RequestBody的一个,它将起作用POST。
这里是工作的解决方案:刚刚从定义自定义转换器String,以Map作为@Component。然后它将自动注册:
@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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3207 次 |
| 最近记录: |