fastjson类库对java对象转json时候时的时间的格式化

来源:互联网 发布:万字酱油 知乎 编辑:程序博客网 时间:2024/06/04 00:44

前言

什么是fastjson?请看github上的答案。

Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景。

出于阿里,当然阿里也自称fastjson是目前java语言中最快的json库,比自称最快的jackson速度要快,到底谁快,我并不知道,但是我会做一个性能测试,关于这几个类库:fastjson jackson gjson json-lib,有兴趣的可以关注一下点击此处。

正文

普通时间格式化

 当我们使用 new Date() 时可以得到一个时间对象,但是是国际标准时间,我们需要对其格式化,并且java也自带了时间格式化类。

//yyyy-MM-dd 年月日//HH:mm:ss.S 时分秒毫秒String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(new Date());//2017-06-27 18:14:33.399//SimpleDateFormat同时提供parse()方法对时间字符串解析

java对象转json时间格式化

   //JSON.toJSONStringWithDateFormat(date, "yyyy-MM-dd HH:mm:ss.SSS")  List<Student> list= new LinkedList<Student>();        Student student = new Student();        student.setName("遇见小星");        for (int i=0;i<3;i++){            student.setId(i);            student.setDate(new Date());            list.add(student);        }   System.out.println(list);    //时间格式化  String data = JSON.toJSONString(list, SerializerFeature.DisableCircularReferenceDetect,   SerializerFeature.WriteDateUseDateFormat);   JSONArray jsonArray = JSON.parseArray(data); //[{"date":"2017-06-27 19:05:14","name":"遇见小星","id":2},{"date":"2017-06-27 //19:05:14","name":"遇见小星","id":2},{"date":"2017-06-27 19:05:14","name":"遇见小星","id":2}]}

 代码中WriteDateUseDateFormat就是时间格式化操作,DisableCircularReferenceDetect是循环引用(没有的可能出现”ref":".jsonArray[0]”})

参考文章

  • https://github.com/alibaba/fastjson/wiki/Samples-DataBind
  • https://github.com/alibaba/fastjson/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
  • 系列化https://github.com/alibaba/fastjson/wiki/%E5%AE%9A%E5%88%B6%E5%BA%8F%E5%88%97%E5%8C%96#1-%E7%AE%80%E4%BB%8B
  • https://github.com/alibaba/fastjson/wiki/Samples-DataBind

阅读全文
0 0