SpringMVC 400错误请求JSON数据

Pio*_*ski 2 spring json http spring-mvc

我向spring mvc控制器发送请求时遇到了一些问题.我有实体:

public class Person {
    private String name;
    private int age;
    private String city;
    //..getters setters

}
Run Code Online (Sandbox Code Playgroud)

和SpringMvc控制器:

@Controller
@RequestMapping("/companies")
public class FirmaController {
    @RequestMapping(value = "/addPerson", method = RequestMethod.POST, headers = {"Content-type=application/json"})
    public String addPerson(@RequestBody Person person) {
        return "person";
    }
}
Run Code Online (Sandbox Code Playgroud)

当我想用curl向服务器发送请求时:

curl -i -X POST -HContent-Type:application/json  -HAccept:application/json http://localhost:8080/api/companies/addPerson -d "{ 'name': 'Gerry', 'age': 20, 'city': 'Sydney' }"
Run Code Online (Sandbox Code Playgroud)

我有一个HTTP/1.1 400错误请求:

HTTP/1.1 400 Bad Request
Content-Type: text/html;charset=ISO-8859-1
Cache-Control: must-revalidate,no-cache,no-store
Content-Length: 1392
Server: Jetty(8.1.10.v20130312) 
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

a b*_*ver 5

您发送的数据不是有效的JSON.字符串必须用双引号括起来,"而不是'像你的例子中的单引号.

如果你没有旧版本的Spring,你应该使用 consumes = "application/json"而不是headers=....