@RequestBody未绑定复杂对象

时间:2018-07-10 20:36:13

标签: spring-mvc spring-boot

我正在尝试使用jsonjavascript对象形式jquery ajax传递给Spring控制器。但是,如果json对象很复杂,那么它就没有约束力。

Javascript:

    var inputParam={};
    inputParam.name="xxx";
    inputParam.address.city="chicago";
    inputParam.address.zip="123456";

    var jqxhr = $.ajax({
            url:"/myurl",
            type:"POST",
            dataType: "html",
            contentType :'application/json',
            data:JSON.stringify(inputparam),
            beforeSend: function( xhr ) {


            }
        });

//Handle a successful call to data service
    jqxhr.done(function(  data, textStatus, jqxhr,response ) {
        // my successful code handle

    });

    //Handle an unsuccessful call to data service
    jqxhr.fail(function(jqXHR, textStatus) {    

        //my error handling code

    });

控制器:

 @RequestMapping(value = "/myurl", method = RequestMethod.POST)
 public String getMyPage(  @RequestBody InputParams inputParam,HttpServletRequest request, Model model ) throws Exception{
        //my code
  }

POJO:

class InputParams {
   private String name;
   private Address address;
  //getter setter
}

class Address{
  private String city;
  private String zip;
  //getter setter
}

我遇到的问题是地址在控制器上没有绑定。

你知道我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

以这种方式设置inputParam,这应该可以解决您的问题

var inputParam={
         name : "xxx",
         address: {
             city :"chicago",
             zip  :"123456"
                 }
           };