我有一个Spring休息 endpoints 做一个简单的hello应用程序 . 它应该接受{“name”:“something”}并返回“Hello,something” .
我的控制器是:
@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!
看起来它不是't deserializing the json into the Person object properly. It'使用默认构造函数然后不设置名称 . 我发现了这个:How to create a POST request in REST to accept a JSON input?所以我尝试在控制器上添加一个@RequestBody,但这会导致一些关于"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported"的错误 . 我看到这里有: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,但与上述冲突...
2 回答
您必须设置
@RequestBody
告诉Spring应该使用什么来设置person
参数 .您必须使用 @RequestMapping(value="/greeting", method=RequestMethod.POST) 设置' produces '
使用下面的代码