天天看點

fastjson使用

在項目中使用到了fastjson,故研究了一下。現将自己的幾個測試用例和大家分享一下~

首先在pom.xml檔案中,加入依賴:

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

建立一個實體類:

public class XwjUser implements Serializable {

    private static final long serialVersionUID = 1L;

    private int id;

    private String message;

    private Date sendTime;

    // 這裡手寫字母大寫,隻是為了測試使用,是不符合java規範的
    private String NodeName;

    private List<Integer> intList;

    public XwjUser() {
        super();
    }

    public XwjUser(int id, String message, Date sendTime) {
        super();
        this.id = id;
        this.message = message;
        this.sendTime = sendTime;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Date getSendTime() {
        return sendTime;
    }

    public void setSendTime(Date sendTime) {
        this.sendTime = sendTime;
    }

    public String getNodeName() {
        return NodeName;
    }

    public void setNodeName(String nodeName) {
        NodeName = nodeName;
    }

    public List<Integer> getIntList() {
        return intList;
    }

    public void setIntList(List<Integer> intList) {
        this.intList = intList;
    }

    @Override
    public String toString() {
        return "XwjUser [id=" + id + ", message=" + message + ", sendTime=" + sendTime + ", intList=" + intList + "]";
    }

}      

接下來看測試用例:

1、對象與json

@Test
    public void testObject() {
        XwjUser user = new XwjUser(1, "Hello World", new Date());
        user.setNodeName("node");

        // 第二個參數為是否格式化json
        String jsonStr = JSON.toJSONString(user, true);
        System.out.println("對象轉為字元串:" + jsonStr);

        XwjUser userDes = JSON.parseObject(jsonStr, XwjUser.class);
        System.out.println("字元串轉為對象:" + userDes);
    }      

運作結果:

對象轉為字元串:{
    "id":1,
    "message":"Hello World",
    "nodeName":"node",
    "sendTime":1525222546733
}
字元串轉為對象:XwjUser [id=1, message=Hello World, sendTime=Wed May 02 08:55:46 CST 2018, intList=null]      

注意事項:

  1、對象轉json字元串時,對象中的NodeName首字母是大寫,轉出來是小寫。

  2、json轉對象時,實體類中一定要加上預設的無參構造器

2、map與json

@Test
    public void testMap() {
        Map<String, Object> testMap = new HashMap<>();
        testMap.put("name", "merry");
        testMap.put("age", 30);
        testMap.put("date", new Date());
        testMap.put("isDel", true);
        testMap.put("user", new XwjUser(1, "Hello World", new Date()));

        String jsonStr = JSON.toJSONString(testMap);
        System.out.println("Map轉為字元串:" + jsonStr);

        Map<String, Object> mapDes = JSON.parseObject(jsonStr, new TypeReference<Map<String, Object>>() {});
        System.out.println("字元串轉map:" + mapDes);
    }      
Map轉為字元串:{"date":1525223256653,"name":"merry","isDel":true,"user":{"id":1,"message":"Hello World","sendTime":1525223256654},"age":30}
字元串轉map:{date=1525223256653, name=merry, isDel=true, user={"id":1,"message":"Hello World","sendTime":1525223256654}, age=30}      

3、list與json

@Test
    public void testMapList() {
        List<Map<String, Object>> mapList = new ArrayList<>();

        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "merry");
        map1.put("age", 30);
        map1.put("date", new Date());
        map1.put("isDel", true);

        Map<String, Object> map2 = new HashMap<>();
        map2.put("name", "jim");
        map2.put("age", 28);
        map2.put("isDel", false);

        mapList.add(map1);
        mapList.add(map2);

        String jsonStr = JSON.toJSONString(mapList);
        System.out.println("list轉為字元串:" + jsonStr);

        // 傳入泛型類型
        List<Map> listDes = JSON.parseArray(jsonStr, Map.class);
        System.out.println("字元串轉為list:" + listDes);
    }      
list轉為字元串:[{"date":1525223309870,"name":"merry","isDel":true,"age":30},{"name":"jim","isDel":false,"age":28}]
字元串轉為list:[{date=1525223309870, name=merry, isDel=true, age=30}, {name=jim, isDel=false, age=28}]      

注意:使用JSON.parseArray時,傳入list中的泛型

4、json中日期格式化

@Test
    public void testDateFormat() {
        Date now = new Date();
        String dateStr = JSON.toJSONString(now);
        System.out.println("預設日期:" + dateStr);

        // 按照指定格式格式化日期,格式為yyyy-MM-dd HH:mm:ss
        String dateStr2 = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
        System.out.println("格式化日期:" + dateStr2);

        String dateStr3 = JSON.toJSONStringWithDateFormat(now, "yyyy-MM-dd HH:mm");
        System.out.println("格式化日期:" + dateStr3);
    }      
預設日期:1525223374867
格式化日期:"2018-05-02 09:09:34"
格式化日期:"2018-05-02 09:09"      

5、json字元串輸出單引号

@Test
    public void testSingleQuotes() {
        List<Object> list = new ArrayList<>();
        list.add("home");
        list.add("hello");
        list.add(true);
        list.add(45.78);
        String listJson = JSON.toJSONString(list, SerializerFeature.UseSingleQuotes);
        System.out.println("轉為單引号字元串:" + listJson);
    }      
轉為單引号字元串:['home','hello',true,45.78]      

6、改變json字元串中預設不輸出值為null字段

@Test
    public void testNull() {
        Map<String, Object> testMap = new HashMap<>();
        testMap.put("name", "merry");
        testMap.put("age", 30);
        testMap.put("date", null);

        // 預設情況下,FastJSON不輸入為值Null的字段
        String jsonStr = JSON.toJSONString(testMap);
        System.out.println("轉為字元串:" + jsonStr);

        String jsonStr2 = JSON.toJSONString(testMap, SerializerFeature.WriteMapNullValue);
        System.out.println("轉為字元串:" + jsonStr2);
    }      
轉為字元串:{"name":"merry","age":30}
轉為字元串:{"date":null,"name":"merry","age":30}      

關于SerializerFeature中的常量屬性含義,可以參考fastjson SerializerFeature詳解

本文示例源碼位址:https://github.com/xuwenjin/xwj_repo/tree/master/xwj-impl

知識改變世界