Json格式數據使用總結

目錄

 

簡介

Json格式數據形式和語法

使用FastJson解析數據

使用JackJson解析數據

前端js解析json數據

 


簡介

Json是一種數據格式,採用key:value的文本格式存儲和表示數據

Json格式數據形式和語法

  1. json對象
    {
    ​
        "ID": 1001,
    ​
        "name": "張三",
    ​
    }
    /*
    特點:
    數據在花括號中數據以"鍵:值"對的形式出現(其中鍵多以字符串形式出現,值可取字符串,數值,甚至其他json對象)
    每兩個"鍵:值"對以逗號分隔(最後一個"鍵:值"對省略逗號)
    */
  2. json對象數組
    {
    ​
        "部門名稱":"研發部",
    ​
        "部門成員":[
    ​
        {"ID": 1001, "name": "張三", "age": 24},
    ​
        {"ID": 1002, "name": "李四", "age": 25},
    ​
        {"ID": 1003, "name": "王五", "age": 22}],
    ​
        "部門位置":"xx樓21號"
    ​
    }
  3. json字符串

    JSON字符串也是在平時開發中使用較多的,json字符串應滿足以下條件:

    1:它必須是一個字符串,由" "或者' '包裹數據,支持字符串的各種操作

    2:裏面的數據格式應該要滿足其中一個格式,可以是json對象,也可以是json對象數組或者是兩種基本形式的組合變形。

使用FastJson解析數據

1.語法

在fastjson包中主要有3個類,JSON,JSONArray,JSONObject

三者之間的關係如下,JSONObject和JSONArray繼承JSON

聯繫上面講到的json基礎知識並對應這三個類,可以發現,JSONObject代表json對象,JSONArray代表json對象數組,JSON代表JSONObject和JSONArray的轉化。

JSONObject類使用

JSONObject實現了Map接口,而json對象中的數據都是以"鍵:值"對形式出現, JSONObject底層操作是由Map實現的。類中主要是get()方法。JSONObject相當於json對象,該類中主要封裝了各種get方法,通過"鍵:值"對中的鍵來獲取其對應的值。

JSONArray類使用

JSONArray的內部是通過List接口中的方法來完成操作的。JSONArray代表json對象數組,json數組對象中存儲的是一個個json對象,所以類中的方法主要用於直接操作json對象。比如其中的add(),remove(),containsAll()方法,對應於json對象的添加,刪除與判斷。 其內部主要由List接口中的對應方法來實現。

跟JSONObject一樣,JSONArray裏面也有一些get()方法,不過不常用,最有用的應該是getJSONObject(int index)方法,該方法用於獲取json對象數組中指定位置的JSONObject對象,配合size()方法,可用於遍歷json對象數組中的各個對象。 通過以上兩個方法,在配合for循環,即可實現json對象數組的遍歷。此外JSONArray中也實現了迭代器方法來遍歷。 通過遍歷得到JSONObject對象,然後再利用JSONObject類中的get()方法,即可實現最終json數據的獲取。

JSON類使用

JSON類主要是實現轉化用的,最後的數據獲取,還是要通過JSONObject和JSONArray來實現。類中的主要是實現json對象,json對象數組,javabean對象,json字符串之間的相互轉化。

2.使用

json字符串—》JSONObject

 

用JSON.parseObject()方法即可將JSon字符串轉化爲JSON對象,利用JSONObject中的get()方法來獲取JSONObject中的相對應的鍵對應的值

//json格式數據---對象類型
String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
System.out.println("StudentName: " + jsonObject.getString("studentName") + "," + "StudentAge: " + jsonObject.getInteger("studentAge"));

JSONObject—》json字符串

用JSON.toJSONString()方法即可將JSON對象轉化爲JSON字符串

JSON字符串數組—》JSONArray

將JSON字符串數組轉化爲JSONArray,通過JSON的parseArray()方法。JSONArray本質上還是一個數組,對其進行遍歷取得其中的JSONObject,然後再利用JSONObject的get()方法取得其中的值。有兩種方式進行遍歷

方式一:通過jsonArray.size()獲取JSONArray中元素的個數,再通過getJSONObject(index)獲取相應位置的JSONObject,循環變量取得JSONArray中的JSONObject,再利用JSONObject的get()進行取值。

方式二:通過jsonArray.iterator()獲取迭代器

JSON_ARRAY_STR = "     [{\"studentName\":\"lily\",\"studentAge\":12}," +
            "{\"studentName\":\"lucy\",\"studentAge\":15}]";
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
// 遍歷方式一
//        int size = jsonArray.size();
//        for(int i = 0;i < size;i++){
//            JSONObject jsonObject = jsonArray.getJSONObject(i);
//            System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
//        }
// 遍歷方式二
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject jsonObject = (JSONObject) iterator.next();
            System.out.println("studentName: " + jsonObject.getString("studentName") + ",StudentAge: " + jsonObject.getInteger("studentAge"));
        }

 

JSONArray—》json字符串

用JSON.toJSONString()方法即可將JSONArray轉化爲JSON字符串

json字符串—》JavaBean

String  JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
// 第一種方式
        JSONObject jsonObject = JSON.parseObject(JSON_OBJ_STR);
        String studentName = jsonObject.getString("studentName");
        Integer studentAge = jsonObject.getInteger("studentAge");
        Student student = new Student(studentName, studentAge);
// 第二種方式,//第二種方式,使用TypeReference<T>類,由於其構造方法使用protected進行修飾,故創建其子類
        Student student1 = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {});
// 第三種方式,通過反射,建議這種方式
        Student student2 = JSON.parseObject(JSON_OBJ_STR, Student.class);

JavaBean —》json字符串

也是通過JSON的toJSONString,不管是JSONObject、JSONArray還是JavaBean轉爲爲JSON字符串都是通過JSON的toJSONString方法。

Student lily = new Student("lily", 12);
String s = JSON.toJSONString(lily);

json字符串數組—》JavaBean-List

JSON_ARRAY_STR = "     [{\"studentName\":\"lily\",\"studentAge\":12}," +
            "{\"studentName\":\"lucy\",\"studentAge\":15}]";
// 方式一:
        JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);
        //遍歷JSONArray
        List<Student> students = new ArrayList<Student>();
        Iterator<Object> iterator = jsonArray.iterator();
        while (iterator.hasNext()){
            JSONObject next = (JSONObject) iterator.next();
            String studentName = next.getString("studentName");
            Integer studentAge = next.getInteger("studentAge");
            Student student = new Student(studentName, studentAge);
            students.add(student);
        }
        // 方式二,使用TypeReference<T>類,由於其構造方法使用protected進行修飾,故創建其子類
        List<Student> studentList = JSON.parseObject(JSON_ARRAY_STR,new TypeReference<ArrayList<Student>>() {});
        // 方式三,使用反射
        List<Student> students1 = JSON.parseArray(JSON_ARRAY_STR, Student.class);
        System.out.println(students1);

 JavaBean-List —》json字符串數組

JavaBean_List到json字符串-數組類型的轉換,直接調用JSON.toJSONString()方法即可

複雜嵌套json格式字符串—》JavaBean_obj

對於複雜嵌套的JSON格式,利用JavaBean進行轉換的時候要注意:

有幾個JSONObject就定義幾個JavaBean

內層的JSONObject對應的JavaBean作爲外層JSONObject對應的JavaBean的一個屬性

public class Student {
    private String studentName;
    private int studentAge;
​
    public Student() {
    }
​
    public Student(String studentName, int studentAge) {
        this.studentName = studentName;
        this.studentAge = studentAge;
    }
​
    public String getStudentName() {
        return studentName;
    }
​
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
​
    public int getStudentAge() {
        return studentAge;
    }
​
    public void setStudentAge(int studentAge) {
        this.studentAge = studentAge;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "studentName='" + studentName + '\'' +
                ", studentAge=" + studentAge +
                '}';
    }
}
​


​
import java.util.List;
​
public class Teacher {
    private String teacherName;
    private int teacherAge;
    private Course course;
    private List<Student> students;
​
    public Teacher() {
    }
​
    public Teacher(String teacherName, int teacherAge, Course course, List<Student> students) {
        this.teacherName = teacherName;
        this.teacherAge = teacherAge;
        this.course = course;
        this.students = students;
    }
​
    public String getTeacherName() {
        return teacherName;
    }
​
    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }
​
    public int getTeacherAge() {
        return teacherAge;
    }
​
    public void setTeacherAge(int 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;
    }
​
    @Override
    public String toString() {
        return "Teacher{" +
                "teacherName='" + teacherName + '\'' +
                ", teacherAge=" + teacherAge +
                ", course=" + course +
                ", students=" + students +
                '}';
    }
}


​
public class Course {
    private String courseName;
    private int code;
​
    public Course() {
    }
​
    public Course(String courseName, int code) {
        this.courseName = courseName;
        this.code = code;
    }
​
    public String getCourseName() {
        return courseName;
    }
​
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
​
    public int getCode() {
        return code;
    }
​
    public void setCode(int code) {
        this.code = code;
    }
​
    @Override
    public String toString() {
        return "Course{" +
                "courseName='" + courseName + '\'' +
                ", code=" + code +
                '}';
    }
}


//第一種方式,使用TypeReference<T>類,由於其構造方法使用protected進行修飾,故創建其子類
    Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, new TypeReference<Teacher>() {});
// 第二種方式,使用反射
    Teacher teacher1 = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);

JavaBean_obj —》複雜json格式字符串

Teacher teacher = JSON.parseObject(COMPLEX_JSON_STR, Teacher.class);
    String s = JSON.toJSONString(teacher);

備註:設置實體中的某個屬性轉json

 

使用JackJson解析數據

 

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
/**
 * JSON工具類
 */
public class JsonUtil {

    /**
     * 將Java對象轉化爲JSON字符串
     */
    public static String getJSON(Object obj) {
        if (null == obj) {
            return "";
        }
        try {
            ObjectMapper mapper = new ObjectMapper();
            //轉換date類型的時候,時間戳
            mapper.getSerializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            String jsonStr = mapper.writeValueAsString(obj);
            return jsonStr;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 將JSON字符串轉化爲Java對象,集合
     */
    public static <T> T getObj(String json, TypeReference<T> ref)
            throws IOException {
        if (null == json || json.length() == 0) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return (T) mapper.readValue(json, ref);
    }

    /**
     * 將JSON字符串轉化爲Java對象,一個對象
     */
    public static Object getObj(String json, Class pojoClass) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(json, pojoClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


}

前端json字符串和對象轉換

1.json字符串=》格式對象 使用json.parse(jsonStr)

2.json格式對象=》json格式字符串,使用JSON.stringify(jsonObj);

var jsonObj = {"name":"張三","age":14};

使用JSON.stringify(jsonObj);

 

三哥交流公衆號:java一號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章