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

Mar*_*ijk 41 rest spring controller spring-mvc

拥有以下代码:

@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作为参数来检索实际的身体,但我想知道是否有更简单的方法?

Mar*_*ijk 70

我发现的最佳方法是:

@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
Run Code Online (Sandbox Code Playgroud)

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

  • 我必须在`HttpEntity &lt;String&gt; httpEntity`之前添加`@ RequestBody`来完成这项工作。希望这可以帮助。 (2认同)

aGO*_*aGO 14

你可以使用

@RequestBody String pBody

  • 这对我不起作用.我收到了一个URL编码的表单数据字符串,其中包含URL查询参数和POST数据,而不是所需数据的原始JSON副本. (2认同)

Jar*_*der 11

只有HttpServletRequest为我工作.HttpEntity给出了空字符串.

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;

@RequestMapping(value = "/greeting", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public String greetingJson(HttpServletRequest request) throws IOException {
    final String json = IOUtils.toString(request.getInputStream());
    System.out.println("json = " + json);
    return "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)

  • 在所有答案中,这个答案很完美 (2认同)
  • String Payload = IOUtils.toString(request.getInputStream(), Charset.forName("UTF8")); (2认同)

小智 7

对我有用的最简单的方法是

@RequestMapping(value = "/greeting", method = POST, consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String greetingJson(String raw) {
    System.out.println("json = " + raw);
    return "OK";
}
Run Code Online (Sandbox Code Playgroud)