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

Aug 11, 2017 am 10:16 AM
java javascript json

本篇文章主要介绍了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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles