这个控制器
@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"
}
我想要的是传递一些带有bar
参数的JSON:http://localhost:8089/temp?foo=7&bar=%7B%22a%22%3A%22b%22%7D,其中foo
是7
而bar
是{"a":"b"}
为什么Spring无法进行这种简单的转换?请注意,如果地图用作@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());
}
}
}
如果你想使用Map<String, String>
,你必须做以下事情:
@GetMapping("temp")
public String temp(@RequestParam Map<String, String> blah) {
System.out.println(blah.get("a"));
return "Hello";
}
这个网址是:http://localhost:8080/temp?a=b
使用Map<String, String>
you可以访问您提供的所有URL请求参数,因此您可以添加?c=d
并使用blah.get("c");
访问控制器中的值
有关更多信息,请参阅:http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-request-param/,参见使用带有@RequestParam的Map以获取多个参数
更新1:如果要将JSON作为String传递,可以尝试以下操作:
如果要映射JSON,则需要定义相应的Java对象,因此对于您的示例,请使用实体进行尝试:
public class YourObject {
private String a;
// getter, setter and NoArgsConstructor
}
然后利用Jackson的ObjectMapper
将JSON字符串映射到Java实体:
@GetMapping("temp")
public String temp(@RequestParam Map<String, String> blah) {
YourObject yourObject =
new ObjectMapper().readValue(blah.get("bar"),
YourObject.class);
return "Hello";
}
有关更多信息/不同的方法,请查看:JSON parameter in spring MVC controller