Skip to content

JacksonSampleDateHandling

Paul Brown edited this page Oct 19, 2011 · 1 revision

<<TableOfContents(4)>>

Custom Date serialization

Default Jackson Date converters can deal with both numeric values (standard Java value of "milliseconds since January 1, 1970, GST") and date formats that JDK's java.text.DateFormat can be configured to read and write (for more details, see JacksonFAQDateHandling).

But sometimes it is necessary to support more complex formats. This is usually easiest to do by writing custom serializers and deserializers. Here is some user-contributed sample code to show how.

JSON Object based dates

(code contributed by Shannon Kendrick)

In this case, goal is to produce dates that have simple JSON object structure like:

  {
    "type" : "Date",
    "value" : "2007-06-30T08:34:09.001Z"
  }

where additional type information is required by recipient (for whatever reason; non-Jackson handler), but the actual date value can be serialized using standard date serializer.

This can be done by code like:

public class ItemFileReadStoreDateSerializer extends JsonSerializer<Date>
{   
    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        DateFormat blueprint = StdDateFormat.getBlueprintISO8601Format();

        // Must create a clone since Formats are not thread-safe:
        DateFormat df = (DateFormat) blueprint.clone();
        jgen.writeStartObject();
        jgen.writeStringField("type", "Date");
        jgen.writeFieldName("value");
        // If standard date format is ok, use this
        provider.defaultSerializeDateValue(date, jgen);
        // (if not, just use whatever converter you want, output result using JsonGenerator)
        jgen.writeEndObject();
    }
}

CategoryJackson