Skip to content Skip to sidebar Skip to footer

Configure Jackson To Parse Multiple Date Formats

I am working on a project where the date formats returned in JSON payloads aren't consistent (that's another issue all together). The project I'm working on uses Jackson to parse t

Solution 1:

Here is a Jackson Multi Date Format Serializer.

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

publicclassMultiDateDeserializerextendsStdDeserializer<Date> {
    privatestaticfinallongserialVersionUID=1L;

    privatestaticfinal String[] DATE_FORMATS = newString[] {
        "MMM dd, yyyy HH:mm:ss",
        "MMM dd, yyyy"
    };

    publicMultiDateDeserializer() {
        this(null);
    }

    publicMultiDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Overridepublic Date deserialize(JsonParser jp, DeserializationContext ctxt)throws IOException, JsonProcessingException {
        JsonNodenode= jp.getCodec().readTree(jp);
        finalStringdate= node.textValue();

        for (String DATE_FORMAT : DATE_FORMATS) {
            try {
                returnnewSimpleDateFormat(DATE_FORMAT).parse(date);
            } catch (ParseException e) {
            }
        }
        thrownewJsonParseException(jp, "Unparseable date: \"" + date + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
    }
}

You can use this simply by annotating a field as follows:

@JsonProperty("date") @JsonDeserialize(using = MultiDateDeserializer.class) final Date date,

Solution 2:

In the meanwhile, an annotation became available for a much simpler solution:

publicclassDateStuff{
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")public Date creationTime;
}

Solution 3:

A better solution is to use StdDateFormat instead. It's Jackson's built-in Date formatter and supports most of the variations of Date formats. Use it like below

StdDateFormatisoDate=newStdDateFormat();
ObjectMappermapper=newObjectMapper();
mapper.setDateFormat(isoDate);

Post a Comment for "Configure Jackson To Parse Multiple Date Formats"