这个控制器
@GetMapping("temp")
public String temp(@RequestParam(value = "foo") int foo,
@RequestParam(value = "bar") Map<String, String> bar) {
return "Hello";
}
产生以下错误:
{
"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"
}
我想要的是传递一些 JSONbar
范围:, where foo
is 7
and bar
is {"a":"b"}
为什么Spring不能完成这个简单的转换?请注意,如果将地图用作@RequestBody
of a POST
要求。
这是有效的解决方案:
只需定义一个自定义转换器String
to Map
as a @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());
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)