Jackson Date Serialize + Deserialize

The Problem
By default, Jackson writes(serialize) date as time stamp number, deserialize from time stamp number and the formats Jackson supported to Date.
SerializationFeature
StdDateFormat - data formats Jackson supports
public final static String DATE_FORMAT_STR_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
'Z' as an alias for "+0000"
protected final static String DATE_FORMAT_STR_ISO8601_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
protected final static String DATE_FORMAT_STR_PLAIN = "yyyy-MM-dd";
protected final static String DATE_FORMAT_STR_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";

But in some cases, we want to serialize date as a more readable string, deserialize from the date string not supported by Jackson by default, and be more lenient.

The Solution
To serialize date as a more readable string, we can configure Jackson's ObjectMapper:
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
objectMapper().setDateFormat(sdf);
To support more date string format, we can create CustomDateDeserializer, and try all formats until one passes.

Jackson's supports parse timestamp number and some date formatted string to date object.
We extend its function to add more supported date format, such as "yyyy-MM-dd"(only date part)

Our CustomDateDeserializer first tries to parse the text as time stamp number, if failed, try all supported date formats until one passes. 

-- As our project uses Solr, I reuse org.apache.solr.common.util.DateUtil, and try all date formats that Jackson and Solr DateUtil support.


public class CustomDateDeserializer extends JsonDeserializer<Date> {
    public static final Collection<String> DEFAULT_DATE_FORMATS = new ArrayList<>();
    static {
        DEFAULT_DATE_FORMATS.addAll(Arrays.asList(JacksonStdDateFormat.getAllFormats()));
        DEFAULT_DATE_FORMATS.addAll(DateUtil.DEFAULT_DATE_FORMATS);
        // we can add other date formats
    }
    static class JacksonStdDateFormat extends StdDateFormat {
        private static final long serialVersionUID = 1L;

        public static String[] getAllFormats() {
            return ALL_FORMATS;
        }
    }
    @Override
    public Date deserialize(final JsonParser jsonparser, final DeserializationContext context) throws IOException {
        final String dateString = jsonparser.getText();
        try {
            return new Date(Long.valueOf(dateString));
        } catch (final Exception e1) {
            return tryParseAsDateString(dateString);
        }
    }

    protected static Date tryParseAsDateString(final String dateString) {
        try {
            // basically DateUtil tries every formats until one passes.
            return DateUtil.parseDate(dateString, DEFAULT_DATE_FORMATS);
        } catch (final ParseException e2) {
            throw new RuntimeException(MessageFormat.format("Unable to parse {0}", dateString));
        }
    }
}

// register CustomDateDeserializer
final SimpleModule dateModule = new SimpleModule().addDeserializer(Date.class, new CustomDateDeserializer());
objectMapper.registerModule(dateModule);
The Complete Code

public void testJacksonDate() throws IOException, ParseException {
    final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    ObjectMapper objectMapper = new ObjectMapper();
    final Model model = new Model();
    final String date = "2016-03-12T20:00:00Z";
    model.setDate(sdf.parse(date));
    String json = objectMapper.writeValueAsString(model);
    // {"date":1457812800000}
    // objectMapper write Date as timestamp number
    System.out.println(json);
    System.out.println(objectMapper.readValue(json, Model.class));

    // https://github.com/FasterXML/jackson-databind/blob/master/src/main/java/com
    /// fasterxml/jackson/databind/util/StdDateFormat.java
    // Be default it can parse string formatted like below:

    // public final static String DATE_FORMAT_STR_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    // https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
    // "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 2001-07-04T12:08:56.235-0700
    // 'Z' as an alias for "+0000"
    // protected final static String DATE_FORMAT_STR_ISO8601_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    // protected final static String DATE_FORMAT_STR_PLAIN = "yyyy-MM-dd";
    // protected final static String DATE_FORMAT_STR_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00Z\"}", Model.class));
    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00.000-0700\"}", Model.class));
    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12\"}", Model.class));
    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00\"}", Model.class));

    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00Z\"}", Model.class));

    // but it doesn't support this:
    try {
        System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12 20:00:00\"}", Model.class));
        fail();
    } catch (final IOException e) {
        e.printStackTrace();
    }

    objectMapper = new ObjectMapper().setDateFormat(sdf);
    // now it will rite date as string: {"date":"2016-03-12T20:00:00Z"}
    json = objectMapper.writeValueAsString(model);
    System.out.println(json);
    assertThat(json, containsString(date));

    // it will use our own date format to format date, and parse string formated date.
    System.out.println(objectMapper.readValue(json, Model.class));
    System.out.println(objectMapper.readValue("{\"date\":1457812800000}", Model.class));

    System.out.println(objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00Z\"}", Model.class));

    // it will not use Jackson's StdDateFormat, so it can't parse the formats StdDateFormat
    // supported
    try {
        // this will fail, no time parts
        objectMapper.readValue("{\"date\":\"2016-03-12\"}", Model.class);
        fail();
    } catch (final IOException e) {
        e.printStackTrace();
    }

    try {
        // this will fail, as missing seconds part
        objectMapper.readValue("{\"date\":\"2016-03-12T20:00Z\"}", Model.class);
        fail();
    } catch (final IOException e) {
        e.printStackTrace();
    }

    try {
        // fail due to the unexpected millseconds part
        objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00.000Z\"}", Model.class);
        fail();
    } catch (final IOException e) {
        e.printStackTrace();
    }

    // The server side wants to support be lenient, accept all different format date string
    // as we use Solr, so we create a CustomDateDeserializer that adds all date formats Jackson
    // supported and Solr Supported.
    final SimpleModule dateModule = new SimpleModule().addDeserializer(Date.class, new CustomDateDeserializer());
    objectMapper = new ObjectMapper().setDateFormat(sdf).registerModule(dateModule);

    // now all pass
    objectMapper.readValue("{\"date\":\"2016-03-12\"}", Model.class);
    objectMapper.readValue("{\"date\":\"2016-03-12T20:00Z\"}", Model.class);
    objectMapper.readValue("{\"date\":\"2016-03-12T20:00:00.000Z\"}", Model.class);
}

Read More
Jackson Essentials - the JSON Libaray
Using Jackson JSON View to Protect Mass Assignment Vulnerabilities
Merge JSON Objects: Jackson + BeanUtils.copyProperties
Jackson Generic Type + Java Type Erasure
Jackson Date Serialize + Deserialize
Post a Comment

Labels

Java (159) Lucene-Solr (110) All (60) Interview (59) J2SE (53) Algorithm (37) Eclipse (35) Soft Skills (35) Code Example (31) Linux (26) JavaScript (23) Spring (22) Windows (22) Web Development (20) Tools (19) Nutch2 (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Chrome (9) Continuous Integration (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Design (8) Dynamic Languages (8) Http Client (8) Maven (8) Security (8) Trouble Shooting (8) bat (8) blogger (8) Big Data (7) Google (7) Guava (7) JSON (7) Problem Solving (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) IDE (5) Lesson Learned (5) Miscs (5) Programmer Skills (5) System Design (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) OpenNLP (4) Project Managment (4) Python (4) Spark (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Firefox (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Google Drive (2) Gson (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Bit Operation (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Troubleshooting (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts