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