View Javadoc
1   /**
2    * Copyright By Grandsoft Company Limited.  
3    * 2014-3-1 下午1:48:05
4    */
5   package gboat2.base.bridge.util.json;
6   
7   import static gboat2.base.bridge.util.DateUtil.SUPPORT_FORMATS;
8   
9   import java.io.IOException;
10  import java.text.ParseException;
11  import java.util.Date;
12  
13  import org.apache.commons.lang3.StringUtils;
14  import org.apache.commons.lang3.time.DateUtils;
15  
16  import com.fasterxml.jackson.core.JsonParser;
17  import com.fasterxml.jackson.core.JsonProcessingException;
18  import com.fasterxml.jackson.databind.DeserializationContext;
19  import com.fasterxml.jackson.databind.JsonDeserializer;
20  import com.fasterxml.jackson.databind.deser.std.DateDeserializers.DateDeserializer;
21  
22  /**
23   * 自定义 jackson 反序列化实现类:将日期字符串反序列化为 {@link java.util.Date} 对象。<br>
24   * 除了支持 jackson 内置 {@link DateDeserializer} 支持的日期格式外,还支持以下日期格式:
25   *  <ul>
26   *  <li>yyyy-MM-dd HH:mm:ss.SSS</li>
27   *  <li>yyyy-MM-dd HH:mm:ss</li>
28   *  <li>yyyy-MM-dd HH:mm</li>
29   *  <li>yyyy-MM-dd</li>
30   *  <li>yyyy-MM-dd'T'HH:mm:ss.SSS</li>
31   *  <li>yyyy-MM-dd'T'HH:mm:ss</li>
32   *  <li>yyyy-MM-dd'T'HH:mm</li>
33   *  <li>yyyy/MM/dd HH:mm:ss.SSS</li>
34   *  <li>yyyy/MM/dd HH:mm:ss</li>
35   *  <li>yyyy/MM/dd HH:mm</li>
36   *  <li>yyyy/MM/dd</li>
37   *  <li>yyyy年MM月dd日 HH时mm分ss秒</li>
38   *  <li>yyyy年MM月dd日 HH时mm分</li>
39   *  <li>yyyy年MM月dd日</li>
40   *  <li>yyyyMMddHHmmssSSS</li>
41   *  <li>yyyyMMddHHmmss</li>
42   *  <li>yyyyMMddHHmm</li>
43   *  <li>yyyyMMdd</li>
44   *  </ul>
45   * <pre>
46   * <code>
47   * public class Example {
48   *     <b>&#64;JsonDeserialize(using = GboatDateDeserializer.class)</b>
49   *     private Date createTime;
50   *     // get, set
51   * }
52   * </code>
53   * </pre>
54   * 
55   * @date 2014-3-1
56   * @author <a href="mailto:[email protected]">何明旺</a>
57   * @since 2.1.2
58   */
59  public class GboatDateDeserializer extends JsonDeserializer<Date> {
60  
61      @Override
62      public Date deserialize(JsonParser jp, DeserializationContext ctxt)
63              throws IOException, JsonProcessingException {
64          try {
65              String value = StringUtils.trim(jp.getValueAsString());
66              return StringUtils.isBlank(value) ? null : DateUtils.parseDate(value, SUPPORT_FORMATS);
67          } catch (ParseException e) {
68              return new DateDeserializer().deserialize(jp, ctxt);
69          }
70      }
71  
72  }