用Spring解码车身参数 [英] Decoding body parameters with Spring

查看:41
本文介绍了用Spring解码车身参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring为Slack App开发一个rest API后端。我能够接收来自Slack的消息(斜杠命令),但我无法正确接收组件交互(按钮单击)。

official documentation表示:

您的操作URL将收到一个HTTP POST请求,其中包括一个负载正文参数,该参数本身包含一个应用程序/x-www-form-urlencode JSON字符串。

因此,我写了以下@RestController

@RequestMapping(method = RequestMethod.POST, value = "/actions", headers = {"content-type=application/x-www-form-urlencoded"})
public ResponseEntity action(@RequestParam("payload") ActionController.Action action) {
    return ResponseEntity.status(HttpStatus.OK).build();
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Action {

    @JsonProperty("type")
    private String type;

    public Action() {}

    public String getType() {
        return type;
    }

}

但是,我收到以下错误:

Failed to convert request element: org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'controllers.ActionController$Action'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'controllers.ActionController$Action': no matching editors or conversion strategy found

这是什么意思,如何解决?

json

您会收到一个包含推荐答案内容的字符串。您没有收到JSON输入,因为application/x-www-form-urlencoded用作内容类型,而不是application/json,如上所述:

您的操作URL将收到一个HTTP POST请求,包括有效负载 Body参数,本身包含一个应用程序/x-www-form-urlencode JSON字符串。

因此将参数类型更改为String,并使用Jackson或任何JSON库将String映射到Action类:

@RequestMapping(method = RequestMethod.POST, value = "/actions", headers = {"content-type=application/x-www-form-urlencoded"})
public ResponseEntity action(@RequestParam("payload") String actionJSON) {
    Action action = objectMapper.readValue(actionJSON, Action.class);  
    return ResponseEntity.status(HttpStatus.OK).build();
}

正如pvpkiran建议的那样,如果您可以直接在POST请求的主体中传递JSON字符串,而不是作为参数值,那么您可以将@RequestParam替换为@RequestBody,但情况似乎并非如此。
实际上,通过使用@RequestBody,请求的主体通过HttpMessageConverter传递以解析方法参数。

作为对您的评论的回应,Spring MVC并没有提供一种非常简单的方法来满足您的需求:将字符串JSON映射到您的Action类。
但是,如果您真的需要自动执行此转换,您可以使用the Spring MVC documentation中所述的冗长替代方法,例如ForMatters(我的重点是):

表示基于字符串的一些带注释的控制器方法参数 请求输入 - ,例如@RequestParam@RequestHeader@PathVariable@MatrixVariable,@CookieValue,如果 参数声明为字符串以外的内容。

对于这种情况,类型转换将根据 已配置的转换器。默认情况下,简单类型,如int、long 支持日期等。类型转换可以通过 WebDataBinder,请参见DataBinder,或通过将ForMatters注册到 FormattingConversionService,请参阅Spring字段格式设置。

通过为Action类创建一个格式化程序(FormatterRegistry子类),您可以将其添加到Spring Web配置as documented

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // ... add action formatter here
    }
}

并在参数声明中使用它:

public ResponseEntity action(@RequestParam("payload") @Action Action actionJ) 
{...}

这篇关于用Spring解码车身参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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