【问题标题】:400 (Bad Request) on passing JSON to Spring controller将 JSON 传递给 Spring 控制器时出现 400(错误请求)
【发布时间】:2016-06-14 14:38:57
【问题描述】:

我正在尝试将对象数组作为 JSON 字符串传递给 Spring 控制器。我的 JSON 格式的数据看起来像

[{
    "id": 123456,
    "name": "First Item"
},
{
    "id": 78910,
    "name": "Second Item"
}]

所以我要发送给控制器

@RequestMapping(value = "/some/url", method = RequestMethod.POST, consumes = "application/json")
public void doSomething(@RequestBody List<CustInfo> myCustInfoList) {
    System.out.println("Message Received " + myCustInfoList);
}

使用此 AJAX 调用

$.ajax({
  type: 'POST',
  url: '/some/url',
  contentType: 'application/json',
  data: '[{"id": 123456, "name": "First Item"}, {"id": 78910, "name": "Second Item"}]',
  success: function () {
            consloe.log("Success");
           }
});

为此,我有两个 bean OuterCoverCustInfo。其中OuterCoverCustInfoCustInfo 的列表有idname

public class OuterCover {

  List<CustInfo> myCustInfoList;

  //getter & setter

}

但我收到了 400(错误请求)。有什么建议吗?

【问题讨论】:

    标签: java jquery json spring-mvc post


    【解决方案1】:

    您需要将 OuterCover 类包含在其他类中,因为请求具有 OuterCover 元素。例如

    class RequestDto{
    
        @JsonElement("outerCover")
        private OuterCover outerCover;
    
        //getters and setters
    }
    

    或者,您可以修改请求负载并删除“outerCover”元素,例如:

    [{
        "id": 123456,
        "name": "First Item"
    },
    {
        "id": 78910,
        "name": "Second Item"
    }]
    

    【讨论】:

    • 如果我想发送data: {[{"id": 123456, "name": "First Item"},{"id": 78910, "name": "Second Item"}]}怎么办
    • 这行得通,我在回答中添加了另一个解决方案。
    • 我不能在控制器中使用OutCover 吗?我想避免再创建一个类 (RequestDto)。
    • 在这种情况下,您需要按照我在回答中的说明修改请求有效负载。
    • 删除 outerCover 仍然给我 400。查看更新的 JSON。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多