JSON基礎:fastjson使用說明

在這裏插入圖片描述
Fastjson雖然最近頻爆問題,但是作爲Json使用較爲廣泛的庫,與Gson、Jackson一起仍然是衆多開發者的重要選擇,即使出於安全的角度考慮,從瞭解fastjson的使用方式以便替換的角度,也需要了解一下fastjson的使用方式,這篇文章進行簡單的總結和整理。

maven引用

使用1.2.70版本是官方目前對於2020年度發現的0-day漏洞的對應的解決方案,建議使用此版或者更新的版本。

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
</dependency>

三個類

fastjson中主要有三個類:

  • JSON
  • JSONObject
  • JSONArray

說明:JSONObject和JSONArray均繼承於JSON類,JSON類本身爲一個抽象類,JSONObject用於json對象處理,JSONArray用於json對象數組處理,由於JSON本身爲抽象類,所以其無法通過實例化來進行相應操作,主要通過其靜態函數進行相關的parse轉化操作。

使用示例

整體說明:三個主要的類中,JSON主要通過使用其靜態函數進行轉換,比如從字符串到Json對象,從Json對象到字符串。JSONObject用於處理Json類,JSONArray用於處理Json數組,就像Json可以組合一樣JSONArray和JSONObject也可以同樣組成複雜的Json結構。

  • JSON定義
public abstract class JSON implements JSONStreamAware, JSONAware {
  • JSONObject定義
public class JSONObject extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler {
  • JSONArray定義
public class JSONArray extends JSON implements List<Object>, Cloneable, RandomAccess, Serializable {

示例1: Json對象和字符串

  • 示例代碼
        final String JSON_PERSON_STRING = "{\"name\":\"liumiao\",\"id\":1001}";
        final JSONObject json = JSON.parseObject(JSON_PERSON_STRING);
        System.out.println("name: " + json.get("name") + " id:" + json.get("id"));
        System.out.println(JSON.toJSONString(json));
  • 執行結果
name: liumiao id:1001
{"name":"liumiao","id":1001}

示例2: Json數組和字符串

  • 示例代碼
        final String JSON_PERSONS_STRING = "[{\"name\":\"liumiao\",\"id\":1001},{\"name\":\"miaoliu\",\"id\":1002}]";
        final JSONArray jsons = JSON.parseArray(JSON_PERSONS_STRING);
        System.out.println(JSON.toJSONString(jsons));

        System.out.println("loop using size()");
        for(int i=0; i<jsons.size(); i++){
            JSONObject json = jsons.getJSONObject(i);
            System.out.println("name: " + json.get("name") + " id:" + json.get("id"));
        }

        System.out.println("loop using iterator");
        Iterator<Object> iterator = jsons.iterator();
        while(iterator.hasNext()) {
            JSONObject json = (JSONObject) iterator.next();
            System.out.println("name: " + json.get("name") + " id:" + json.get("id"));
        }
  • 執行結果
[{"name":"liumiao","id":1001},{"name":"miaoliu","id":1002}]
loop using size()
name: liumiao id:1001
name: miaoliu id:1002
loop using iterator
name: liumiao id:1001
name: miaoliu id:1002

示例3: Json組合結構和字符串

  • 示例代碼
        final String JSON_PERSONS_STRING = "[{\"name\":\"liumiao\",\"id\":1001,\"courses\":" +
                "[{\"course\":\"math\",\"score\":90},{\"course\":\"english\",\"score\":80}]}," +
                "{\"name\":\"miaoliu\",\"id\":1002,,\"courses\":" +
                "[{\"course\":\"math\",\"score\":80},{\"course\":\"english\",\"score\":90}]}]";

        final JSONArray jsons = JSON.parseArray(JSON_PERSONS_STRING);
        System.out.println(JSON.toJSONString(jsons));

        System.out.println("loop using size()");
        for (int i = 0; i < jsons.size(); i++) {
            JSONObject json = jsons.getJSONObject(i);
            System.out.println("name: " + json.get("name") + " id:" + json.get("id"));
            JSONArray courses = json.getJSONArray("courses");
            for(int j=0; j<courses.size(); j++) {
                JSONObject course = courses.getJSONObject(j);
                System.out.println("course: " + course.get("course") + " score:" + course.get("score"));
            }
        }

        System.out.println("loop using iterator");
        Iterator<Object> iterator = jsons.iterator();
        while (iterator.hasNext()) {
            JSONObject json = (JSONObject) iterator.next();
            System.out.println("name: " + json.get("name") + " id:" + json.get("id"));

            JSONArray courses = json.getJSONArray("courses");
            Iterator<Object> courseIterator = courses.iterator();
            while(courseIterator.hasNext()){
                JSONObject course = (JSONObject) courseIterator.next();
                System.out.println("course: " + course.get("course") + " score:" + course.get("score"));
            }
        }
  • 執行結果
[{"courses":[{"score":90,"course":"math"},{"score":80,"course":"english"}],"name":"liumiao","id":1001},{"courses":[{"score":80,"course":"math"},{"score":90,"course":"english"}],"name":"miaoliu","id":1002}]
loop using size()
name: liumiao id:1001
course: math score:90
course: english score:80
name: miaoliu id:1002
course: math score:80
course: english score:90
loop using iterator
name: liumiao id:1001
course: math score:90
course: english score:80
name: miaoliu id:1002
course: math score:80
course: english score:90

示例4: Json對象和JavaBean

  • 示例代碼
public class Person {
    private int id;
    private String name;

    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 Person(int id, String name) {
        this.id = id;
        this.name= name;
    }
}

轉化示例代碼

        final String JSON_PERSON_STRING = "{\"name\":\"liumiao\",\"id\":1001}";
        final JSONObject json = JSON.parseObject(JSON_PERSON_STRING);
        String name = json.getString("name");

        System.out.println("name: " + json.get("name") + " id:" + json.get("id"));
        // using new
        Person person1 = new Person(json.getInteger("id"),json.getString("name"));
        System.out.println(JSON.toJSONString(person1));

        // using JSON.parsObject
        Person person2 = JSON.parseObject(JSON_PERSON_STRING, Person.class);
        System.out.println(JSON.toJSONString(person2));

        // using JSON.parsObject
        Person person3 = JSON.parseObject(JSON_PERSON_STRING, new TypeReference<Person>() {});
        System.out.println(JSON.toJSONString(person3));
  • 執行結果
name: liumiao id:1001
{"id":1001,"name":"liumiao"}
{"id":1001,"name":"liumiao"}
{"id":1001,"name":"liumiao"}

示例5: Json數組和JavaBean

  • 示例代碼
        final String JSON_PERSONS_STRING = "[{\"name\":\"liumiao\",\"id\":1001},{\"name\":\"miaoliu\",\"id\":1002}]";
        final JSONArray jsons = JSON.parseArray(JSON_PERSONS_STRING);
        System.out.println(JSON.toJSONString(jsons));

        List<Person> personList1 = new ArrayList<Person>();
        Iterator<Object> iterator = jsons.iterator();

        while(iterator.hasNext()) {
            JSONObject json = (JSONObject) iterator.next();
            personList1.add(new Person(json.getInteger("id"),json.getString("name")));
        }
        System.out.println(JSON.toJSONString(personList1));

        List<Person> personList2 = JSON.parseArray(JSON_PERSONS_STRING,Person.class);
        System.out.println(JSON.toJSONString(personList2));

        List<Person> personList3 = JSON.parseObject(JSON_PERSONS_STRING, new TypeReference<ArrayList<Person>>() {});
        System.out.println(JSON.toJSONString(personList3));

        List<Person> personList4 = new ArrayList<Person>();
        personList4.add(new Person(2001,"liu"));
        personList4.add(new Person(2002,"miao"));
        personList4.add(new Person(2003,"liumiao"));
        System.out.println(JSON.toJSONString(personList4));
  • 執行結果
[{"name":"liumiao","id":1001},{"name":"miaoliu","id":1002}]
[{"id":1001,"name":"liumiao"},{"id":1002,"name":"miaoliu"}]
[{"id":1001,"name":"liumiao"},{"id":1002,"name":"miaoliu"}]
[{"id":1001,"name":"liumiao"},{"id":1002,"name":"miaoliu"}]
[{"id":2001,"name":"liu"},{"id":2002,"name":"miao"},{"id":2003,"name":"liumiao"}]

示例6: Json組合結構和JavaBean

  • 示例代碼
public class Person {
    private int id;
    private String name;
    private List<Course> courses;

    public List<Course> getCourses() {
        return courses;
    }

    public void setCourses(List<Course> courses) {
        this.courses = courses;
    }

    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 Person(int id, String name, List<Course> courses) {
        this.id = id;
        this.name= name;
        this.courses=courses;
    }
}

public class Course {
    private String course;
    private int score;

    public String getCourse() {
        return course;
    }

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

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}
        final String JSON_PERSON_STRING = "{\"name\":\"liumiao\",\"id\":1001,\"courses\":" +
                "[{\"course\":\"math\",\"score\":90},{\"course\":\"english\",\"score\":80}]}";

        final JSONObject json = JSON.parseObject(JSON_PERSON_STRING);
        System.out.println(JSON.toJSONString(json));

        Person person1 = JSON.parseObject(JSON_PERSON_STRING, Person.class);
        System.out.println(JSON.toJSONString(person1));

        Person person2 = JSON.parseObject(JSON_PERSON_STRING,new TypeReference<Person>() {});
        System.out.println(JSON.toJSONString(person2));
  • 執行結果
{"courses":[{"score":90,"course":"math"},{"score":80,"course":"english"}],"name":"liumiao","id":1001}
{"courses":[{"course":"math","score":90},{"course":"english","score":80}],"id":1001,"name":"liumiao"}
{"courses":[{"course":"math","score":90},{"course":"english","score":80}],"id":1001,"name":"liumiao"}

參考內容

https://github.com/alibaba/fastjson
https://github.com/alibaba/fastjson/wiki/Quick-Start-CN
https://mvnrepository.com/artifact/com.alibaba/fastjson/

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