您会收到一个包含 JSON 内容的字符串。您没有收到 JSON 输入application/x-www-form-urlencoded
用作内容类型而不是application/json
就像声明的那样 :
您的操作 URL 将收到 HTTP POST 请求,包括有效负载
body 参数,本身包含 application/x-www-form-urlencoded
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 所建议的,你可以替换@RequestParam
by @RequestBody
如果您可以直接在 POST 请求正文中传递 JSON 字符串,而不是作为参数值传递,但情况似乎并非如此。
确实通过使用@RequestBody
,请求的正文通过HttpMessageConverter
解决方法参数。
为了回答您的评论,Spring MVC 没有提供一种非常简单的方法来实现您的要求:将字符串 JSON 映射到您的Action
class.
但如果您确实需要自动化此转换,您有一个冗长的替代方案,如中所述Spring MVC 文档 https://docs.spring.io/spring/docs/5.1.0.RC2/spring-framework-reference/web.html#mvc-ann-typeconversion例如格式化程序(重点是我的):
一些带注释的控制器方法参数,表示基于字符串
请求输入 — 例如@RequestParam
, @RequestHeader
, @PathVariable
,
@MatrixVariable,
and @CookieValue
,如果
argument 被声明为 String 之外的其他内容。
对于这种情况,类型转换会根据
配置的转换器。默认情况下简单类型,如 int、long、
支持日期等。类型转换可以通过自定义
WebDataBinder,请参阅 DataBinder,或通过向
FormattingConversionService,请参阅 Spring 字段格式化。
通过创建格式化程序(FormatterRegistry
子类)为你的Action
您可以在 Spring Web 配置中添加该类据记录 https://docs.spring.io/spring/docs/5.1.0.RC2/spring-framework-reference/web.html#mvc-config-conversion :
@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)
{...}