springboot之json传参(后台控制层如何接收和解析参数)

一般web端都是用form标签的形式进行表单提交到后台,后台控制层再用相应的实体对象去接收前端传来的json参数。

但是有时候前端界面很复杂,要传入后端的参数是各种标签里面的value值,这些值又是来自不同实体对象,所以后台接收参数就会变成一个麻烦事。

我现在采取的措施是,后端控制层用一个map参数接分别来自三个不同对象的属性。不过要事先在前端封装好json对象。

(实际场景是微信公账号)

1.前端代码

submitSave:function (){
                    
                    var data = {
                        "visitorInfo":{},//预约信息
                        "license":{},//车辆信息
                        "user":{}//当前登录用户信息

                    };
                    data.license.carNo = vm.carNo;
                    data.visitorInfo.originatorType = vm.userType;
                    data.visitorInfo.createId = vm.createId;
                    data.visitorInfo.userId = vm.userId;
                    data.visitorInfo.receiverId = vm.receiverId;
                    data.visitorInfo.invitationReason = vm.invitationReason;
                    data.visitorInfo.ddr = vm.ddr;
                    data.visitorInfo.invitationTime = vm.invitationTime;
                    data.visitorInfo.endTime = vm.endTime;
                    data.user.id = vm.dengluId;

                    // console.log(JSON.stringify(data))
                    $.ajax({
                        url: '${ctx}/mobile/submit',
                        dataType: 'json',
                        contentType : 'application/json;charset=utf-8',//缺少这个415
                        type: 'post',
                        data: JSON.stringify(data),//缺少这个400
                        success: function (data) {
                            console.log(data);
                            if (data.status == 1) {
                                setTimeout(function () {
                                    // mui.back();
                                    //跳到首页
                                    window.location.href =     '${ctx}/mobile/toIndex';
                                }, 1000)
                            }
                            if(data.status == 0){

                            }
                            if(data.msg != ''){
                                mui.toast(data.msg);
                            }


                        }
                    });
                },

2.后台代码(中间map用阿里的fastjson解析)

/**
     * 提交和修改按钮接口
     */
    @ResponseBody
    @PostMapping("/submit")public ResponseEntity<Response> submit(@RequestBody Map<String,Object> map,HttpServletRequest request) {

        Map<String,String> map1 = (Map) map.get("visitorInfo");
        Map<String,String> map2 = (Map) map.get("license");
        Map<String,String> map3 = (Map) map.get("user");

        VisitorInfo visitorInfo = JSON.parseObject(JSON.toJSONString(map1), VisitorInfo.class);
        License license = JSON.parseObject(JSON.toJSONString(map2), License.class);
        UserInfo user = JSON.parseObject(JSON.toJSONString(map3), UserInfo.class);
}
原文地址:https://www.cnblogs.com/bbllw/p/11149322.html