Spring MVC中@RequestParam中的JSON数组

时间:2015-03-25 06:37:30

标签: json spring

我将以下JSON发送到控制器并尝试访问它但我得到了#34;客户端发送的请求在语法上是不正确的。"错误信息。

JSON:

{
"employees": [
{
    "firstName": "John",
    "lastName": "Doe"
},
{
    "firstName": "Anna",
    "lastName": "Smith"
},
{
    "firstName": "Peter",
    "lastName": "Jones"
}
]}

控制器:

@RequestMapping(value="/xyz",produces="application/json",consumes="application/json",method=RequestMethod.POST)
public String sendEmpDetails(@RequestBody List<Employee> employeeList){
    return "xyz";
}

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

你正在使用一个复杂的对象,但只需要一个List数组,所以像这样构建你的JSON:

    var items = [];
    {
        var item = {};
        item ["firstName"] = "John";
        item ["lastName"] = "Doe";
        items.push(item);
    }
    {
        var item = {};
        item ["firstName"] = "Anna";
        item ["lastName"] = "Smith";
        items.push(item);
    }
    {
        var item = {};
        item ["firstName"] = "Peter";
        item ["lastName"] = "Jones";
        items.push(item);
    }
    $.ajax({
        url: '/myurl',
        data: JSON.stringify(items),
        type: 'POST',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            alert(response);
        },
        error: function (xhr, status, errorThrown) {
            alert(errorThrown);
        }
    }