spring - 如何在 Spring REST Controller 中访问普通的 json 主体?

标签 spring rest spring-mvc controller

有以下代码:

@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!";
}

尽管 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);
}

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

最佳答案

到目前为止我发现的最佳方法是:

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpEntity<String> httpEntity) {
    String json = httpEntity.getBody();
    // json contains the plain json string

如果有其他选择,请告诉我。

关于spring - 如何在 Spring REST Controller 中访问普通的 json 主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17866996/

相关文章:

java.lang.NoClassDefFoundError : org/springframework/web/method/annotation/ExceptionMethodMapping

java - 无法在 spring 框架中将 freemarker 模板的编码更改为 UTF-8

SpringBoot : Unable to find a single main class from the following candidates

spring - 如何通过Spring JdbcTemplate生成动态的 "in (...)"sql列表?

java - DefaultCookieSerializer.setJvmRoute 不工作

java - 使用 ObjectMapper 反序列化对象时将驼峰命名法转换为下划线

javascript - PHP通知: Trying to get property of non-object

web-services - 每个线程具有不同参数的 JMeter 测试计划

asp.net-mvc - 选择哪个:ASP.NET MVC或RESTful WCF?

javascript - 在 AngularJs 单页应用程序中发布请求