Set Jackson Timezone for Date deserialization

后端 未结 9 621
终归单人心
终归单人心 2020-12-13 04:23

I\'m using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {\"enrollDate\":\"2011-09-28

9条回答
  •  心在旅途
    2020-12-13 05:00

    I am using Jackson 1.9.7 and I found that doing the following does not solve my serialization/deserialization timezone issue:

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    objectMapper.setDateFormat(dateFormat);
    

    Instead of "2014-02-13T20:09:09.859Z" I get "2014-02-13T08:09:09.859+0000" in the JSON message which is obviously incorrect. I don't have time to step through the Jackson library source code to figure out why this occurs, however I found that if I just specify the Jackson provided ISO8601DateFormat class to the ObjectMapper.setDateFormat method the date is correct.

    Except this doesn't put the milliseconds in the format which is what I want so I sub-classed the ISO8601DateFormat class and overrode the format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) method.

    /**
     * Provides a ISO8601 date format implementation that includes milliseconds
     *
     */
    public class ISO8601DateFormatWithMillis extends ISO8601DateFormat {
    
      /**
       * For serialization
       */
      private static final long serialVersionUID = 2672976499021731672L;
    
    
      @Override
      public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
      {
          String value = ISO8601Utils.format(date, true);
          toAppendTo.append(value);
          return toAppendTo;
      }
    }
    

提交回复
热议问题