Spring rest json post null值

Mic*_*elB 5 java rest spring json

我有一个Spring休息端点做一个简单的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());
    }

}
Run Code Online (Sandbox Code Playgroud)

人:

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

当我向服务提出请求时

curl -X POST -d '{"name": "something"}' http://localhost:8081/testapp/greeting
Run Code Online (Sandbox Code Playgroud)

我明白了

Hello, World!
Run Code Online (Sandbox Code Playgroud)

看起来它没有正确地将json反序列化为Person对象.它使用默认构造函数,然后不设置名称.我发现了这个:如何在REST中创建POST请求以接受JSON输入?所以我尝试在控制器上添加一个@RequestBody,但这会导致一些关于"内容类型'应用程序/ x-www-form-urlencoded; charset = UTF-8'不受支持"的错误.我看到这里有:@RequestBody MultiValueMap不支持内容类型'application/x-www-form-urlencoded; charset = UTF-8',建议删除@RequestBody

我已经尝试删除它不喜欢的默认构造函数.

这个问题涵盖了空值REST Web服务使用Spring MVC在发布JSON时返回null但它建议添加@RequestBody但是与上面的冲突...

Zor*_*ube 11

你必须设置@RequestBody告诉Spring应该使用什么来设置你的person参数.

 public Greeting greeting(@RequestBody Person person) {
    return new Greeting(counter.incrementAndGet(), String.format(template, person.getName()));
} 
Run Code Online (Sandbox Code Playgroud)