1. 程式人生 > 實用技巧 >筆記_使用FastJson匯出JSON

筆記_使用FastJson匯出JSON

FastJson

概要

  • 速度:

    • fastjson是目前java語言中最快的json庫,比自稱最快的jackson速度要快

    • fastjson比gson快大約6倍,

  • 網站:

FastJson常用方法

public static final Object parse(String text); // 把JSON文字parse為JSONObject或者JSONArray 
public static final JSONObject parseObject(String text)// 把JSON文字parse成JSONObject
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文字parse為JavaBean
public static final JSONArray parseArray(String text); // 把JSON文字parse成JSONArray
public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文字parse成JavaBean集合
public static final String toJSONString(Object object); // 將JavaBean序列化為JSON文字
public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化為帶格式的JSON文字
public static final Object toJSON(Object javaObject); //將JavaBean轉換為JSONObject或者JSONArray。

Java ==> JSON

步驟

  • step1. 匯入jar包

  • step2. 構建POJO結構

  • step3. 將POJO轉換為JSON字串:

    • JSON.toJSONString( 頂級POJO物件的引用 )

      => 純字串,只有一行

    • JSON.toJSONString( 頂級POJO物件的引用, true) => 帶格式

常用的方法

// 1)將JavaBean序列化為JSON文字 
public static final String toJSONString(Object object);

// 2)將JavaBean序列化為帶格式的JSON文字
public static final String toJSONString(Object object, boolean prettyFormat);

一個簡單的Demo

  • User.java

    package josn.simple;

    public class User {
    private String username;
    private String password;

    public User() {}

    public User(String username, String password) {
    super();
    this.username = username;
    this.password = password;
    }

    public String getUsername() {
    return username;
    }

    public void setUsername(String username) {
    this.username = username;
    }

    public String getPassword() {
    return password;
    }

    public void setPassword(String password) {
    this.password = password;
    }

    @Override
    public String toString() {
    return "User [username=" + username + ", password=" + password + "]";
    }
    }
  • UserGroup.java

    package josn.simple;

    import java.util.ArrayList;
    import java.util.List;

    public class UserGroup {
    private String name;
    private List<User> users;

    public UserGroup() {
    users = new ArrayList<User>();
    }

    public UserGroup(String name, List<User> users) {
    super();
    this.name = name;
    this.users = users;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public List<User> getUsers() {
    return users;
    }

    public void setUsers(List<User> users) {
    this.users = users;
    }

    @Override
    public String toString() {
    return "UserGroup [name=" + name + ", users=" + users + "]";
    }
    }
  • TestFastJson.java

    package josn.simple;

    import java.util.ArrayList;
    import java.util.List;

    import org.junit.Test;

    import com.alibaba.fastjson.JSON;
    public class TestFastJson {
    @Test
    public void objectToJson() {
    // 簡單的Java類轉Json
    User user = new User("ali", "123456");
    String userJson = JSON.toJSONString(user);
    System.out.println("簡單Java類轉Json字串:"+ userJson);

    // List<Object>類轉Json
    User user1 = new User("coco", "123456");
    User user2 = new User("ly", "789");

    List<User> users = new ArrayList<User>();
    users.add(user1);
    users.add(user2);

    String listJson = JSON.toJSONString(users);
    System.out.println("List<Object>轉Json字串" + listJson);

    // 複雜的Java類轉Json字串
    UserGroup userGroup = new UserGroup("userGroup", users);
    String userGroupJson = JSON.toJSONString(userGroup);
    System.out.println("複雜的Java類轉Json字串:" + userGroupJson);
    }
    }
  • 控制檯輸出結果:

    簡單Java類轉Json字串:{"password":"123456","username":"ali"}
    List<Object>轉Json字串:[{"password":"123456","username":"coco"},{"password":"789","username":"ly"}]
    複雜的Java類轉Json字串:{"name":"userGroup","users":[{"password":"123456","username":"coco"},{"password":"789","username":"ly"}]}

我的一個Demo

  • User.java

    package josn.mydemo;

    public class User {
    private int id;
    private String name;
    private Computer computer;
    public User() {
    super();
    }
    public User(int id, String name, Computer computer) {
    super();
    this.id = id;
    this.name = name;
    this.computer = computer;
    }
    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 Computer getComputer() {
    return computer;
    }
    public void setComputer(Computer computer) {
    this.computer = computer;
    }
    @Override
    public String toString() {
    return "User [id=" + id + ", name=" + name + ", computer=" + computer
    + "]";
    }
    }
  • Computer.java

    package josn.mydemo;

    public class Computer {
    private String brand;
    private String CPUdegree;
    public Computer() {
    super();
    }
    public Computer(String brand, String cPUdegree) {
    super();
    this.brand = brand;
    CPUdegree = cPUdegree;
    }
    public String getBrand() {
    return brand;
    }
    public void setBrand(String brand) {
    this.brand = brand;
    }
    public String getCPUdegree() {
    return CPUdegree;
    }
    public void setCPUdegree(String cPUdegree) {
    CPUdegree = cPUdegree;
    }
    @Override
    public String toString() {
    return "Computer [brand=" + brand + ", CPUdegree=" + CPUdegree + "]";
    }
    }
  • TestObject.java

    package josn.mydemo;

    import org.junit.Test;

    import com.alibaba.fastjson.JSON;

    public class TestObject {
    @Test
    public void test() {
    Computer computer = new Computer("Thinkpad", "intel core i7");
    User user = new User(1, "大白", computer);
    String userJson = JSON.toJSONString(user);
    System.out.println(userJson);
    }
    }
  • 結果:

練習題:一個複雜的Demo

題目

[
{
"id": "user_list",
"key": "id",
"tableName": "使用者列表",
"className": "cn.dmego.domain.User",
"column": [
{
"key": "rowIndex",
"header": "序號",
"width": "50",
"allowSort": "false"
},
{
"key": "id",
"header": "id",
"hidden": "true"
},
{
"key": "name",
"header": "姓名",
"width": "100",
"allowSort": "true"
}
]
},
{
"id": "role_list",
"key": "id",
"tableName": "角色列表",
"className": "cn.dmego.domain.Role",
"column": [
{
"key": "rowIndex",
"header": "序號",
"width": "50",
"allowSort": "false"
},
{
"key": "id",
"header": "id",
"hidden": "true"
},
{
"key": "name",
"header": "名稱",
"width": "100",
"allowSort": "true"
}
]
}
]

解答

  • Column.java

    package josn.complex;

    public class Column {
    private String key;
    private String header;
    private Integer width;
    private Boolean allowSort;
    private Boolean hidden;

    public Column() {

    }

    public Column(String key, String header, Boolean hidden) {
    super();
    this.key = key;
    this.header = header;
    this.hidden = hidden;
    }

    public Column(String key, String header, Integer width, Boolean allowSort) {
    super();
    this.key = key;
    this.header = header;
    this.width = width;
    this.allowSort = allowSort;
    }

    public String getKey() {
    return key;
    }
    public void setKey(String key) {
    this.key = key;
    }
    public String getHeader() {
    return header;
    }
    public void setHeader(String header) {
    this.header = header;
    }
    public Integer getWidth() {
    return width;
    }
    public void setWidth(Integer width) {
    this.width = width;
    }
    public Boolean isAllowSort() {
    return allowSort;
    }
    public void setAllowSort(Boolean allowSort) {
    this.allowSort = allowSort;
    }
    public Boolean isHidden() {
    return hidden;
    }
    public void setHidden(Boolean hidden) {
    this.hidden = hidden;
    }

    @Override
    public String toString() {
    return "Column [key=" + key + ", header=" + header + ", width=" + width
    + ", allowSort=" + allowSort + ", hidden=" + hidden + "]";
    }

    }
  • Query.java

    package josn.complex;

    import java.util.List;


    public class Query {
    private String id;
    private String key;
    private String tableName;
    private String className;
    private List<Column> columns;

    public Query(String id, String key, String tableName, String className,
    List<Column> columns) {
    super();
    this.id = id;
    this.key = key;
    this.tableName = tableName;
    this.className = className;
    this.columns = columns;
    }
    public String getId() {
    return id;
    }
    public void setId(String id) {
    this.id = id;
    }
    public String getKey() {
    return key;
    }
    public void setKey(String key) {
    this.key = key;
    }
    public String getTableName() {
    return tableName;
    }
    public void setTableName(String tableName) {
    this.tableName = tableName;
    }
    public String getClassName() {
    return className;
    }
    public void setClassName(String className) {
    this.className = className;
    }
    public List<Column> getColumns() {
    return columns;
    }
    public void setColumns(List<Column> columns) {
    this.columns = columns;
    }
    }
  • Test.java

    package josn.complex;

    import java.util.ArrayList;
    import java.util.List;

    import com.alibaba.fastjson.JSON;


    public class Test {

    public static void main(String[] args) {
    List<Query> queries = new ArrayList<Query>();

    // 建立query1
    List<Column> columns1 = new ArrayList<Column>();
    Column column1 = new Column("RowIndex", "序號", 50, false);
    Column column2 = new Column("id", "id", true);
    Column column3 = new Column("name", "姓名", 100, true);
    columns1.add(column1);
    columns1.add(column2);
    columns1.add(column3);

    Query query1 = new Query("user_list", "id", "使用者列表", "cn.dmego.domain.User", columns1);
    queries.add(query1);

    // 建立query2
    List<Column> columns2 = new ArrayList<Column>();
    Column column4 = new Column("RowIndex", "序號", 50, false);
    Column column5 = new Column("id", "id", true);
    Column column6 = new Column("name", "姓名", 100, true);
    columns2.add(column4);
    columns2.add(column5);
    columns2.add(column6);

    Query query2 = new Query("role_list", "id", "角色列表", "cn.dmego.domain.Role", columns2);
    queries.add(query2);

    // 轉化為JSON
    String json = JSON.toJSONString(queries, true);
    System.out.println(json);
    }

    }

筆記

  • 由裡到外,先定義最裡面的物件

  • 在fastjson中,預設是不輸出空值的。無論Map中的null和物件屬性中的null,序列化的時候都會被忽略不輸出,這樣會減少產生文字的大小。 => 來自官方文件