FastJson學習:JSON格式字符串、JSON對象及JavaBean之間的相互轉換


當前台需要傳送一系列相似數據到后端時,可以考慮將其組裝成json數組對象,然后轉化為json形式的字符串傳輸到后台

例如:

            nodes = $('#PmPbsSelect_tree').tree('getChecked');
            var data=[];
            for(var i=0;i<nodes.length;i++){
                if(!isParentCheck(nodes[i],nodes)){
                    data.push({"id":nodes[i].id,
                        "pid":node.id});
                }else{
                    data.push({"id":nodes[i].id,
                        "pid":null});
                }
            }    
            dataStr=JSON.stringify(data);    
            $.ajax({
                 url:ctx+"/PmWbs/savePmWbsByModel",
                 type:"POST",
                 data:{"dataStr":dataStr,
                     "projectId":pmProjectSelect.combobox('getValue')},
                 success:function(data){
                     basetree.tree('reload');
                 },
                 error:function(){
                     alert("請求失敗");
                 },
                 dataType:"json"
             });      

接下來闡述正文:(其實是copy其他人的博客,主要放在自己博客下面好找...........................)

==================華麗的分割線=======================================

fastJson對於json格式字符串的解析主要用到了一下三個類:

JSON:fastJson的解析器,用於JSON格式字符串與JSON對象及javaBean之間的轉換。

JSONObject:fastJson提供的json對象。

JSONArray:fastJson提供json數組對象。

首先定義了三個json格式的字符串作為我們的數據源

//json字符串-簡單對象型
private static final String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
//json字符串-數組類型
private static final String  JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
//復雜格式json字符串
private static final String  COMPLEX_JSON_STR = "{\"teacherName\":\"crystall\",
\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},
\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";

 

一、JSON格式字符串與JSON對象之間的轉換。

1.json字符串-簡單對象型 與 JSONObject之間的轉換

JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
//因為JSONObject繼承了JSON,所以這樣也是可以的
//JSONObject jsonObject1 = JSONObject.parseObject(JSON_OBJ_STR); 

2.json字符串-數組類型與JSONArray之間的轉換

JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
//因為JSONArray繼承了JSON,所以這樣也是可以的
//JSONArray jsonArray1 = JSONArray.parseArray(JSON_ARRAY_STR);

        //遍歷方式1
        int size = jsonArray.size();
        for (int i = 0; i < size; i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
        }

        //遍歷方式2
        for (Object obj : jsonArray) {
            JSONObject jsonObject = (JSONObject) obj;
        }
    

3.復雜json格式字符串與JSONObject之間的轉換

JSONObject jsonObject = JSON.parseObject(COMPLEX_JSON_STR);
//因為JSONObject繼承了JSON,所以這樣也是可以的
//JSONObject jsonObject1 = JSONObject.parseObject(COMPLEX_JSON_STR);
        
        String teacherName = jsonObject.getString("teacherName");
        Integer teacherAge = jsonObject.getInteger("teacherAge");
        JSONObject course = jsonObject.getJSONObject("course");
        JSONArray students = jsonObject.getJSONArray("students");

 此時獲取到了json字符串的數組,再對各個字符串進行解析

 

二、JSON格式字符串與javaBean之間的轉換

首先,我們針對數據源所示的字符串,提供三個javaBean。

public class Student {

    private String studentName;
    private Integer studentAge;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
}




public class Course {

    private String courseName;
    private Integer code;

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}



public class Teacher {

    private String teacherName;
    private Integer teacherAge;
    private Course course;
    private List<Student> students;

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    public Integer getTeacherAge() {
        return teacherAge;
    }

    public void setTeacherAge(Integer teacherAge) {
        this.teacherAge = teacherAge;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

json字符串與javaBean之間的轉換推薦使用 TypeReference<T> 這個類,使用泛型可以更加清晰,當然也有其它的轉換方式,這里就不做探討了。

1.json字符串-簡單對象型與javaBean之間的轉換

Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {}); 
//因為JSONObject繼承了JSON,所以這樣也是可以的
 //Student student1 = JSONObject.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});

2.json字符串-數組類型與javaBean之間的轉換

ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});
//因為JSONArray繼承了JSON,所以這樣也是可以的
//ArrayList<Student> students1 = JSONArray.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});


免責聲明!

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



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