Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 the JSON responses. Right now I've written a few de/serializers to handle it but it's not elegant.

I want to know whether there's a way to configure Jackson with a set of possible date formats to parse for a particular response rather than writing several separate deserializers for each format. Similar to how GSON handles the problem in this question

like image 236
Kurian Vithayathil Avatar asked Jul 23 '14 14:07

Kurian Vithayathil


3 Answers

Here is a Jackson Multi Date Format Serializer.

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;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * https://stackoverflow.com/a/42567051/11152683
 */
public class MultiDateDeserializer extends StdDeserializer<Date> {
    private static final long serialVersionUID = 1L;

    private static final SimpleDateFormat[] DATE_FORMATTERS = new SimpleDateFormat[]{
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm' UTC'")
    };

    public MultiDateDeserializer() {
        this(null);
    }

    public MultiDateDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        final String date = node.textValue();

        for (SimpleDateFormat formatter : DATE_FORMATTERS) {
            try {
                return formatter.parse(date); //.toInstant();
            } catch (ParseException e) {
            }
        }
        throw new JsonParseException(jp, "Unparseable date: \"" + date + "\". Supported formats: " +
                Arrays.stream(DATE_FORMATTERS).map(SimpleDateFormat::toPattern).collect(Collectors.joining("; ")));
    }
}

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

@JsonProperty("date") @JsonDeserialize(using = MultiDateDeserializer.class) final Date date,
like image 145
rouble Avatar answered Nov 17 '22 21:11

rouble


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

public class DateStuff {
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd,HH:00", timezone="CET")
    public Date creationTime;
}
like image 36
Keno Avatar answered Nov 17 '22 20:11

Keno


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

StdDateFormat isoDate = new StdDateFormat();
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(isoDate);
like image 1
Code_Worm Avatar answered Nov 17 '22 22:11

Code_Worm