无法在Spring REST控制器中将Map用作JSON @RequestParam [英] Cannot use Map as a JSON @RequestParam in Spring REST controller

查看:273
本文介绍了无法在Spring REST控制器中将Map用作JSON @RequestParam的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此控制器

@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 ,其中foo7,而bar{"a":"b"} 为什么Spring无法进行这种简单的转换?请注意,如果将地图用作POST请求的@RequestBody,则它起作用.

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.

推荐答案

以下是有效的解决方案: 只需将自StringMap的自定义转换器定义为@Component.然后它将自动注册:

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());
        }
    }
}

这篇关于无法在Spring REST控制器中将Map用作JSON @RequestParam的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆