如何在Spring Rest Controller中访问普通的JSON主体? [英] How to access plain json body in Spring rest controller?

查看:108
本文介绍了如何在Spring Rest Controller中访问普通的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!";
}

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

The String json argument is always null despite json being sent in the body.

请注意,我不需要自动类型转换,我只是想要简单的json结果.

Note that I don't want automatic type conversion, I just want the plain json result.

例如,此方法有效:

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

Probably I can use the use the ServletRequest or InputStream as argument to retrieve the actual body, but I wonder if there is an easier way?

推荐答案

直到现在我发现的最佳方式是:

Best way I found until now is:

@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

让我知道是否还有其他选择.

Let me know if there are other alternatives.

这篇关于如何在Spring Rest Controller中访问普通的JSON主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆