相关疑难解决方法(0)

如何访问Spring休息控制器中的普通json主体?

拥有以下代码:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody String json) {
    System.out.println("json = " + json); // TODO json is null... how to retrieve plain json body?
    return "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)

尽管json在正文中发送,但String json参数始终为null.

请注意,我不想要自动类型转换,我只想要普通的json结果.

这例如有效:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(@RequestBody User user) {
    return String.format("Hello %s!", user);
}
Run Code Online (Sandbox Code Playgroud)

可能我可以使用ServletRequest或InputStream作为参数来检索实际的身体,但我想知道是否有更简单的方法?

rest spring controller spring-mvc

41
推荐指数
4
解决办法
6万
查看次数

标签 统计

controller ×1

rest ×1

spring ×1

spring-mvc ×1