无法在Spring REST控制器中将Map用作JSON @RequestParam

问题描述 投票:1回答:2

这个控制器

@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,其中foo7bar{"a":"b"}为什么Spring无法进行这种简单的转换?请注意,如果地图用作@RequestBody请求的POST,则它可以正常工作。

spring spring-boot spring-restcontroller http-request-parameters
2个回答
4
投票

这是有效的解决方案:只需将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());
        }
    }
}

3
投票

如果你想使用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

© www.soinside.com 2019 - 2024. All rights reserved.