• 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

  • 相关阅读:
    [ACM] POJ 3687 Labeling Balls (拓扑排序,反向生成端)
    xml和json选择奖
    android 如何分析java.lang.IllegalArgumentException: Cannot draw recycled bitmaps异常
    代码农民提高生产力
    &#39;Basic&#39; attribute type should not be a persistence entity/a container
    13 适配器
    密码学基础知识(四)分组密码
    PKCS #1 RSA Encryption Version 1.5 填充方式
    rsa加密--选择padding模式需要注意的问题。。。
    RSA PKCS1 填充方式
  • 原文地址:https://www.cnblogs.com/xuwenjin/p/8978687.html
Copyright © 2020-2023  润新知