Spring Rest JSON发布空值 [英] Spring rest json post null values
问题描述
我有一个Spring rest终结点,它在做一个简单的hello应用程序.它应该接受{"name":"something"}并返回"Hello,something".
I have a Spring rest endpoint doing a simple hello app. It should accept a {"name":"something"} and return "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!
好像没有正确地将json反序列化为Person对象.它使用的是默认构造函数,然后未设置名称.我发现了这一点:如何在REST中创建POST请求以接受JSON输入?,所以我尝试在控制器上添加@RequestBody,但这会导致一些有关内容类型'application/x-www-form-urlencoded; charset = UTF- 8'不支持".我在这里看到了它的内容:内容@RequestBody MultiValueMap不支持输入'application/x-www-form-urlencoded; charset = UTF-8',建议删除@RequestBody
Looks like it isn't deserializing the json into the Person object properly. It's using the default constructor and then not setting the name. I found this: How to create a POST request in REST to accept a JSON input? so I tried adding an @RequestBody on the controller but that causes some error about "Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported". I see that is covered here: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap which suggests removing the @RequestBody
我尝试删除也不喜欢的默认构造函数.
I have tried removing the default constructor which it doesn't like either.
此问题涵盖了空值使用Spring的REST Web服务MVC在发布JSON时返回null ,但建议添加@RequestBody,但这与上面的冲突...
This question covers null values REST webservice using Spring MVC returning null while posting JSON but it suggests adding @RequestBody but that conflicts with above...
推荐答案
您必须设置@RequestBody
告诉Spring应该使用什么来设置person
param.
You must set the @RequestBody
to tell to Spring what should be use to set your person
param.
public Greeting greeting(@RequestBody Person person) {
return new Greeting(counter.incrementAndGet(), String.format(template, person.getName()));
}
这篇关于Spring Rest JSON发布空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!