springMVC參數綁定JSON類型的數據


需求就是:

現在保存一個Student,並且保存Student的friend,一個student會有多個朋友,這里要傳遞到后台的參數是:

var friends = new Array();
    var o1 = {
        "family": "大宅門",
        "otherName": "lisi",
        "desc": "親密無間的好朋友"
    }

    var o2 = {
        "family": "軍大院",
        "otherName": "wangwu",
        "desc": "關系一般"
    }

    friends.push(o1);
    friends.push(o2);

//要傳遞的參數:id=1 name=zhangsan age=10是要保存的student信息,並且friends是student的朋友信息;
data:{
            "id": 1,
            "name": "zhangsan",
            "age": 10,
            "friends":friends
        },

 

一、包裝類型來接收JSON類型的傳參:                                                                                           

方法一其實就是 springMVC學習(11)-json數據交互和RESTful支持 中接收json數據;只不過包裝了另一個po

前台代碼,ajax傳遞數據:

<input type="button" onclick="saveFriend()" value="保存friend" />
<script type="text/javascript">
/**
 * 保存朋友
 */
function saveFriend(){
    var friends = new Array();
    var o1 = {
        "family": "大宅門",
        "otherName": "lisi",
        "desc": "親密無間的好朋友"
    }

    var o2 = {
        "family": "軍大院",
        "otherName": "wangwu",
        "desc": "關系一般"
    }

    friends.push(o1);
    friends.push(o2);
    
    //要發送的參數
    var params = {
        "id": 1,
        "name": "zhangsan",
        "age": 10,
        "friends":friends    
    };
    
    $.ajax({
        type: 'post',
        url: '${pageContext.request.contextPath }/saveStudent',
        contentType:'application/json;charset=utf-8',
        dataType: 'json',
        data: JSON.stringify(params),
        success: function(data){
            console.log(data);
        }
    });
}
</script>

Controller中接受這個參數:

/**
     * 保存朋友
     */
    @RequestMapping("/saveStudent")
    @ResponseBody
    public void saveStudent(@RequestBody StudendAndFriend studendAndFriend){
        System.out.println("接收參數friends--->> " + studendAndFriend);
    }

接收參數的包裝類:

StudendAndFriend.java:

package com.cy.po;

import java.util.List;

/**
 * 接收參數包裝類
 * @author chengyu
 *
 */
public class StudendAndFriend {
    private int id;
    private String name;
    private int age;
    private List<Friend> friends;
    
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public List<Friend> getFriends() {
        return friends;
    }
    public void setFriends(List<Friend> friends) {
        this.friends = friends;
    }
    
    
}
View Code

Friend.java:

package com.cy.po;

public class Friend {
    private String family;
    private String otherName;
    private String desc;
    
    
    public String getFamily() {
        return family;
    }
    public void setFamily(String family) {
        this.family = family;
    }
    public String getOtherName() {
        return otherName;
    }
    public void setOtherName(String otherName) {
        this.otherName = otherName;
    }
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
    
    @Override
    public String toString() {
        return "Friend [family=" + family + ", otherName=" + otherName
                + ", desc=" + desc + "]";
    }
    
}
View Code

后台成功接收參:

注意點:

ajax傳參:

contentType:'application/json;charset=utf-8'; //contentType為application/json

data: JSON.stringify(params),           //傳的是字符串;

 

 

方法二、                                              

傳遞String類型的json字符串過來,后台接收后,進行JSONArray解析成對應的List<Object>;

這里使用fastjson-1.2.2.jar包來對json字符串轉化為javabean類型;

前端發送請求:

<input type="button" onclick="saveFriend2()" value="保存friend2" />
<script type="text/javascript">
/**
 * 保存朋友2
 */
function saveFriend2(){
    var friends = new Array();
    var o1 = {
        "family": "大宅門",
        "otherName": "lisi",
        "desc": "親密無間的好朋友"
    }

    var o2 = {
        "family": "軍大院",
        "otherName": "wangwu",
        "desc": "關系一般"
    }

    friends.push(o1);
    friends.push(o2);
    
    friends = JSON.stringify(friends);
    
    $.ajax({
        type: 'post',
        url: '${pageContext.request.contextPath }/saveStudent2',
        dataType: 'json',
        data: {
            "id": 1,
            "name": "zhangsan",
            "age": 10,
            "friends":friends    
        },
        success: function(data){
            console.log(data);
        }
    });
}
</script>

Controller接收這個參數:

   //用的是fastjson 

    import com.alibaba.fastjson.JSONArray;
    import com.cy.po.Friend;


  /**
* 保存朋友2 */ @RequestMapping("/saveStudent2") @ResponseBody public void saveStudent2(int id, String name, int age, String friends){ List<Friend> frientList = JSONArray.parseArray(friends, Friend.class); System.out.println("接收參數friends--->> " + frientList); }

可以看到前端發送參數:

controller中經過json解析為javabean:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM