JSON复杂结构传参到后台


一般情况下,json传参基本都是{key:value,key:value}这种无嵌套模式传参到后台,这样后台无需做处理,直接对应实体或key名称类型对应即可
但偶尔也需要既传递 {key:value} 也要传递 value下的嵌套数据 如{key:value,key:[0,1,2,3,4]}

这种复杂参数,需要使用到JSON.stringify()将参数序列化后string后进行传递到后台解析
常见的两种方案如下
1.在不改变请求头的情况下,后台依旧原生类型接收
2.在改变头的情况下,后台需要 @RequestBody注解 接收参数

 

第一种方案
前端操作 也可直接使用$.get $.post 直接操作

        var testarray=new Array();
        testarray.push({id:11,name:'hahha'});
     testarray.push({id:12,name:'hahha'});
var testdata = {key:1,array:JSON.stringify(testarray)}; $.ajax({ url: "test01", type:"post",//post get async:true,// default true data:testdata, complate:function(){ }, error:function(){ }, success: function(result){ if(result.status==1){ alert("请求成功!"); }else{ alert("请求失败"); } } });

后台 操作
参数接收 String key,String array
打印操作 System.out.println(key+"------"+array);
打印结果 1------[{"id":11,"name":"hahha"},{"id":12,"name":"hahha"}]
后台 自行针对array使用JSONObject(fastjson)转换处理

第二种方案

 前端定义ajax参数

     var testarray=new Array();
        testarray.push({id:11,name:'hahha'});
        testarray.push({id:12,name:'hahha'});
        var testdata = {key:1,array:testarray};
        $.ajax({
            url: "test01", 
            type:"post",//post get
            async:true,// default true 
            data: JSON.stringify(testdata),
            dataType:"json",// xml html script json jsonp text
            contentType:"application/json;charset=UTF-8",
            complate:function(){ 
            },
            error:function(){  
            },
            success: function(result){
                if(result.status==1){
                    alert("请求成功!");
                }else{
                    alert("请求失败");
                }
            }
        });

后台操作
参数接收 @RequestBody JSONObject json
打印 System.out.println(json);
打印结果 {"array":[{"id":11,"name":"hahha"},{"id":12,"name":"hahha"}],"key":1}
后台自行针对json 取出需要的参数操作

总结 JSON.stringify()用于复杂json传参到后台,如果没有嵌套json或array,不需要使用;
对以上两种方案,个人更倾向于第一种方案,无需前端调整请求参数,在后台接收到指定的需要转化的key后使用JSONObject(fastjson)转换取值即可

 

 参考文档 https://www.cnblogs.com/htoooth/p/7242217.html

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM