JSON parameter in spring MVC controller

后端 未结 5 556
感动是毒
感动是毒 2020-11-27 04:51

I have

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
SessionInfo register(UserProfile profileJson){
  ...
}

I pass profileJson

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 05:38

    This does solve my immediate issue, but I'm still curious as to how you might pass in multiple JSON objects via an AJAX call.

    The best way to do this is to have a wrapper object that contains the two (or multiple) objects you want to pass. You then construct your JSON object as an array of the two objects i.e.

    [
      {
        "name" : "object1",
        "prop1" : "foo",
        "prop2" : "bar"
      },
      {
        "name" : "object2",
        "prop1" : "hello",
        "prop2" : "world"
      }
    ]
    

    Then in your controller method you recieve the request body as a single object and extract the two contained objects. i.e:

    @RequestMapping(value="/handlePost", method = RequestMethod.POST, consumes = {      "application/json" })
    public void doPost(@RequestBody WrapperObject wrapperObj) { 
         Object obj1 = wrapperObj.getObj1;
         Object obj2 = wrapperObj.getObj2;
    
         //Do what you want with the objects...
    
    
    }
    

    The wrapper object would look something like...

    public class WrapperObject {    
    private Object obj1;
    private Object obj2;
    
    public Object getObj1() {
        return obj1;
    }
    public void setObj1(Object obj1) {
        this.obj1 = obj1;
    }
    public Object getObj2() {
        return obj2;
    }
    public void setObj2(Object obj2) {
        this.obj2 = obj2;
    }   
    
    }
    

提交回复
热议问题