当前位置: 移动技术网 > IT编程>开发语言>Java > java如何利用FastJSON、Gson、Jackson三种Json格式工具自定义时间序列化

java如何利用FastJSON、Gson、Jackson三种Json格式工具自定义时间序列化

2019年07月19日  | 移动技术网IT编程  | 我要评论

清远汽车站,cctv1晚间新闻,神舟国旅集团

java处理json数据有三个比较流行的类库fastjson、gson和jackson。

jackson

jackson是由其社区进行维护,简单易用并且性能也相对高些。但是对于复杂的bean转换json,转换的格式鄙视标准的json格式。ps:jackson为spring mvc内置json解析工具

gson

gson是由谷歌公司研发的产品,目前是最全的json解析工具。完全可以将复杂的类型的json解析成bean或者bean到json的转换

fastjson

fastjson是一个java语言编写的高性能的json处理器,由阿里巴巴公司开发。fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库。但是在对一些复杂类型的bean转换json上会出现一些问题,需要特殊处理。

1.遇到的问题

在java平台通过接口调用.net提供的服务的时候,在json序列化的时候,经常遇到时间格式的转换的不对的问题。
.net平台内置的json序列化使用的是system.runtime.serialization,序列化出来的时间是下面的这种格式

\/date(1296576000000+0800)\/

2.思路

为了能够调用.net平台提供的服务,那么在时间格式(date)序列化的时候,能够序列化成上面的格式。那么就拼时间字符串。

date now = new date();
string nowstr = string.format("\\/date(%s+0800)\\/", now.gettime());

3.代码

依赖jar包

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.1'
compile group: 'com.alibaba', name: 'fastjson', version: '1.2.36'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.0'

自定义时间转化字符串代码

public class stringsmallutils {

  /**
   * 时间类型格式转换为指定的string类型
   *
   * @param date
   * @return
   */
  protected static string datetospecialstring(date date) {
    if (date == null)
      return null;
    return string.format("\\/date(%s+0800)\\/", date.gettime());
  }

  /**
   * 指定的string类型转换为时间类型格式
   *
   * @param str
   * @return
   */
  protected static date specialstringtodate(string str) {
    if (isempty(str))
      return null;
    if (!contains(str,"date"))
      return null;
    str = str.replace("\\/date(", "").replace("+0800)\\/", "").trim();
    return new date(long.parselong(str));
  }


  /**
   * 判断字符串是否包含输入的字符串
   *
   * @param str
   * @param searchstr
   * @return
   */
  public static boolean contains(string str, string searchstr) {
    if (str == null || searchstr == null) {
      return false;
    }
    return str.contains(searchstr);
  }

  /**
   * 判断字符串是否为空
   *
   * @param str
   * @return
   */
  public static boolean isempty(string str) {
    return ((str == null) || (str.trim().isempty()));
  }
}

3.1 gson自定义实现date json字符串序列化

gson自定义json序列类只需要实现jsonserializer<t>接口,以及反序列化接口jsondeserializer<t>

public class gsoncustomerdatejsonserializer implements jsonserializer<date>, jsondeserializer<date> {
  @override
  public jsonelement serialize(date src, type typeofsrc, jsonserializationcontext context) {
    return new jsonprimitive(stringsmallutils.datetospecialstring(src));
  }

  @override
  public date deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception {
    return stringsmallutils.specialstringtodate(json.getasstring());
  }
}

测试

gson的自定义的序列化类是通过适配器模式进行注册到gson上的。

public class program {
  public static void main(string[] args) throws jsonprocessingexception {
    date start = new date();
    gson gson = new gsonbuilder().registertypeadapter(date.class, new gsoncustomerdatejsonserializer()).create();
    string gsonstr = gson.tojson(createuser());
    date end = new date();
    long interval = (end.gettime() - start.gettime());
    system.out.println(string.format("gson序列化之后的字符串:%s,花费时间%d毫秒", gsonstr, interval));
  }

  private static user createuser() {
    user user = new user();
    user.setname("张三");
    user.setage(21);
    user.setlastlogintime(new date());
    return user;
  }
}

3.2 fasjson自定义实现date json字符串序列化

fastjson自定义序列化只需要实现objectserializer接口,以及反序列化接口objectdeserializer

public class fastjsoncustomerdatejsonserializer implements objectserializer, objectdeserializer {
  @override
  public void write(jsonserializer serializer, object object, object fieldname, type fieldtype, int features) throws ioexception {
    serializewriter out = serializer.getwriter();
    out.write(stringsmallutils.datetospecialstring((date) object));
  }

  @override
  public <t> t deserialze(defaultjsonparser parser, type type, object fieldname) {
    return (t) stringsmallutils.specialstringtodate(parser.getinput());
  }

  @override
  public int getfastmatchtoken() {
    return 0;
  }
}

测试

fastjson自定义的序列化类是通过serializeconfig内部维护的serializersmap对象

public class program {
  public static void main(string[] args) throws jsonprocessingexception {
    date start1 = new date();
    serializeconfig mapping = new serializeconfig();
    mapping.put(date.class, new fastjsoncustomerdatejsonserializer());
    string fastjsonstr = json.tojsonstring(createuser(), mapping);
    date end1 = new date();
    long interval1 = (end1.gettime() - start1.gettime());
    system.out.println(string.format("fastjson序列化之后的字符串:%s,花费时间%d毫秒", fastjsonstr, interval1));
  }

  private static user createuser() {
    user user = new user();
    user.setname("张三");
    user.setage(21);
    user.setlastlogintime(new date());
    return user;
  }
}

3.3 jackson自定义实现date json字符串序列化

jackson自定义的序列化的类需要继承jsondeserializer<t>。由于java只能单向继承,所以jackson的自定义反序列化的类就需要再新建一个反序列化的类继承jsondeserializer<t>类

public class jacksoncustomerdatejsonserializer extends jsonserializer<date> {
  @override
  public void serialize(date value, jsongenerator gen, serializerprovider serializers) throws ioexception {
    gen.writestring(stringsmallutils.datetospecialstring(value));
  }
}
public class jacksoncustomerdatejsondeserializer extends jsondeserializer<date> {
  @override
  public date deserialize(jsonparser p, deserializationcontext ctxt) throws ioexception, jsonprocessingexception {
    return stringsmallutils.specialstringtodate(p.gettext());
  }
}

测试

jackson自定义的序列化类需要通过registermodule。也就是需要将新建的序列化类注册到simplemodule

public class program {
  public static void main(string[] args) throws jsonprocessingexception {
    date start2 = new date();
    objectmapper mapper = new objectmapper();
    simplemodule module = new simplemodule();
    module.addserializer(date.class, new jacksoncustomerdatejsonserializer());
    module.adddeserializer(date.class, new jacksoncustomerdatejsondeserializer());
    mapper.registermodule(module);
    string jacksonstr = mapper.writevalueasstring(createuser());
    date end2 = new date();
    long interval2 = (end2.gettime() - start2.gettime());
    system.out.println(string.format("jackson序列化之后的字符串:%s,花费时间%d毫秒", jacksonstr, interval2));
  }

  private static user createuser() {
    user user = new user();
    user.setname("张三");
    user.setage(21);
    user.setlastlogintime(new date());
    return user;
  }
}

4.总结

上面三种最终运行的时间及结果如下:

  • gson序列化之后的字符串:{"name":"张三","age":21,"lastlogintime":"\\/date(1502366214027+0800)\\/"},花费时间77毫秒
  • fastjson序列化之后的字符串:{"age":21,"lastlogintime":\/date(1502366214100+0800)\/,"name":"张三"},花费时间99毫秒
  • jackson序列化之后的字符串:{"name":"张三","age":21,"lastlogintime":"\\/date(1502366214307+0800)\\/"},花费时间200毫秒

1.就代码实现方式上,gson与fastjson的实现方式优于jackson。面向接口编程。

2.就注册方式上,gson优于fastjson与jackson。使用了适配器模型

3.就运行效率上,gson与fastjson的效率优于jackson。gson相当于jackson的三倍,fastjson是jackson的二倍。

在实际项目,优先考虑使用gson与fastjson

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网