繁体   English   中英

Spring MVC中@RequestParam中的JSON数组

[英]Array of JSON in @RequestParam in Spring MVC

我正在将以下JSON发送到控制器并尝试访问它,但是我收到“客户端发送的请求在语法上不正确”。 错误信息。

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

我在这里做错了什么?

您正在使用复杂的对象,但只需要一个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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM