我正在为backend开发一个REST后端和Spring。我能够接收来自Slack (斜杠命令)的消息,但是我无法正确地接收组件交互(单击按钮)。
正式文件说:
Action将接收一个HTTP请求,包括一个负载主体参数,该参数本身包含一个应用程序/x form-urlencoded字符串。
因此,我编写了以下@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这意味着什么,以及如何解决?
发布于 2018-08-30 08:02:02
您将收到一个包含JSON内容的字符串。您没有收到JSON输入,因为application/x-www-form-urlencoded用作内容类型,而不是application/json,如所述:
Action将接收一个HTTP请求,包括一个负载主体参数,该参数本身包含一个应用程序/x form-urlencoded字符串。
因此,将参数类型更改为String,并使用杰克逊或任何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所建议的,如果您可以将JSON字符串直接传递到POST请求的正文中,而不是作为参数的值传递,则可以用@RequestParam替换为@RequestBody,但情况似乎并非如此。
实际上,通过使用@RequestBody,请求的主体通过一个HttpMessageConverter来解析方法参数。
为了回答您的评论,Spring没有提供一种非常简单的方法来实现您的需求:将字符串JSON映射到您的Action类。
但是,如果您确实需要将此转换自动化,那么您将有一个冗长的备选方案,如Spring文档中所述(强调是我的):
一些表示基于字符串的请求输入的带注释的控制器方法参数,例如
@RequestParam、@RequestHeader、@PathVariable、@MatrixVariable,和@CookieValue,如果参数声明为字符串以外的东西,则可能需要类型转换。 在这种情况下,基于配置的转换器自动应用类型转换。默认情况下,支持简单类型,如int、long、Date等。类型转换可以通过WebDataBinder进行自定义,参见DataBinder,或者通过向FormattingConversionService注册Formatting,请参阅Spring格式.
通过为您的FormatterRegistry类创建一个格式化程序( Action子类),您可以将其添加到Spring 如文件所示中:
@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)
{...}发布于 2018-08-30 14:11:03
为了简单起见,您可以使用下面的代码块。@Request body将有效负载映射到Action类。它还验证以确保类型不是空的。javax.validation包中的@Valid和@NotBlank。
@PostMapping("actions")
public ResponseEntity<?> startApplication(@RequestBody @Valid Action payload) {
// use your payload here
return ResponseEntity.ok('done');
}
class Action {
@NotBlank
private String type;
public Action() {
}
public String getType() {
return type;
}
}https://stackoverflow.com/questions/52091841
复制相似问题