SpringMVC 400错误请求JSON数据

时间:2014-01-12 19:29:34

标签: json spring http spring-mvc

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

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

}

和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";
    }
}

当我想用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' }"

我有 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) 

我做错了什么?

2 个答案:

答案 0 :(得分:5)

您发送的数据无效JSON。字符串必须用双引号"包装而不是单引号',就像你的例子一样。

如果您没有旧版本的Spring,则应使用consumes = "application/json"代替headers=...

答案 1 :(得分:3)

这是正确的:

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