Home > Java > javaTutorial > Java uses Json format tools (FastJSON, Gson, Jackson) to implement custom time serialization examples

Java uses Json format tools (FastJSON, Gson, Jackson) to implement custom time serialization examples

黄舟
Release: 2017-08-11 10:16:43
Original
2880 people have browsed it

本篇文章主要介绍了java如何利用FastJSON、Gson、Jackson三种Json格式工具自定义时间序列化,具有一定的参考价值,有兴趣的可以了解一下

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)\/
Copy after login

2.思路

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


Date now = new Date();
String nowStr = String.format("\\/Date(%s+0800)\\/", now.getTime());
Copy after login

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'
Copy after login

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


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()));
  }
}
Copy after login

3.1 Gson自定义实现Date Json字符串序列化

Gson自定义Json序列类只需要实现JsonSerializer接口,以及反序列化接口JsonDeserializer


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());
  }
}
Copy after login

测试

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;
  }
}
Copy after login

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;
  }
}
Copy after login

测试

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;
  }
}
Copy after login

3.3 Jackson自定义实现Date Json字符串序列化

Jackson自定义的序列化的类需要继承JsonDeserializer。由于Java只能单向继承,所以Jackson的自定义反序列化的类就需要再新建一个反序列化的类继承JsonDeserializer


public class JacksonCustomerDateJsonSerializer extends JsonSerializer<Date> {
  @Override
  public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeString(StringSmallUtils.DateToSpecialString(value));
  }
}
Copy after login


public class JacksonCustomerDateJsonDeserializer extends JsonDeserializer<Date> {
  @Override
  public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    return StringSmallUtils.SpecialStringToDate(p.getText());
  }
}
Copy after login

测试

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;
  }
}
Copy after login

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

The above is the detailed content of Java uses Json format tools (FastJSON, Gson, Jackson) to implement custom time serialization examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template