我有一个 Spring rest 端点正在执行一个简单的 hello 应用程序。它应该接受 {"name":"something"} 并返回“Hello, something”。
我的 Controller 是:
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
@RequestMapping(value="/greeting", method=RequestMethod.POST)
public String greeting(Person person) {
return String.format(template, person.getName());
}
}
人:
public class Person {
private String name;
public Person() {
this.name = "World";
}
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
当我像这样向服务发出请求时
curl -X POST -d '{"name": "something"}' http://localhost:8081/testapp/greeting
我明白了
Hello, World!
看起来它没有正确地将 json 反序列化为 Person 对象。它使用默认构造函数,然后不设置名称。我发现了这个:How to create a POST request in REST to accept a JSON input?所以我尝试在 Controller 上添加一个@RequestBody,但这会导致一些关于“不支持内容类型‘application/x-www-form-urlencoded;charset=UTF-8’”的错误。我看到这里有介绍:Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap这建议删除@RequestBody
我已经尝试删除它也不喜欢的默认构造函数。
这个问题涵盖空值 REST webservice using Spring MVC returning null while posting JSON但它建议添加 @RequestBody 但这与上述冲突...
最佳答案
您必须设置 @RequestBody
来告诉 Spring 应该使用什么来设置您的 person
参数。
public Greeting greeting(@RequestBody Person person) {
return new Greeting(counter.incrementAndGet(), String.format(template, person.getName()));
}
关于java - Spring rest json 发布空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373421/