springMVC接受对象实体并且对象实体里面又有对象集合方式

springMVC接受对象实体并且对象实体里面又有对象集合方式:

Ajax:

function add(){
    var orders = [
        {
            orderNo : "H222255"
        },
        {
            orderNo : "H222256"
        }
    ]
    var user = {
        username : "刘亚超",
        password : "ab0715",
        orderList : orders
    }
    debugger;
    $.ajax({
        url: '/store/api/test/add.json',
        type: "POST",
        data: JSON.stringify(user),//将对象序列化成JSON字符串
        dataType: "json",
        contentType : 'application/json;charset=utf-8', //设置请求头信息
        async: false,
        success: function (result) {
            debugger;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            debugger;
            alert("出错了");
        }
    })
}

说明:

1.

   data: JSON.stringify(user),//将对象序列化成JSON字符串
        dataType: "json",
        contentType : 'application/json;charset=utf-8', //设置请求头信息
   缺一不可,否则会报错。

2.

   add.json没有错误;

   如果是add.html后缀,springmvc默认会采用[text/html]编码。所以,后缀使用别的后缀或者,不用后缀就可以了。

Controller接受:

@RequestMapping("/add")
@ResponseBody
public BaseResponse test(@RequestBody UserParam userParam){
  //用户重置
  userParam.setUsername("李雪雷");
  userParam.setPassword("66666");
  return BaseResponse.successCustom().setData(userParam).build();
}

说明:

   @RequestBody不能去掉,否则会报错

原文地址:https://www.cnblogs.com/super-chao/p/8258164.html