1

I am using the @JsonFormat annotation from the fasterxml.jackson library:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date endDate;

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date startDateInUtc;

When the date format isn't correct, I don't get an exception, but instead, get the wrong date object (e.g. month 13 becomes January).

Based on my research, I came across two possible solutions:

  1. Playing with the ObjectMapper. (with the setDateFormat function)
  2. Creating my own Json Deserializer class, that will throw an error when the format is not valid:
public class JsonDateDeserializer extends JsonDeserializer<Date> {
    
    public static final String DATE_FORMAT = "yyyy-MM-dd";

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
        format.setLenient(false);
        String dateString = jsonParser.getText();
        try {
            return format.parse(dateString);
        } catch (ParseException e) {
            throw new InvalidFormatException(String.format("Date format should be %s", DATE_FORMAT), dateString, Date.class);
        }
    }
}

With neither solution can I specify a different format for different fields.

Although I can define multiple deserializers, it looks to me like a pretty ugly way to do this.

I thought that the @JsonFormat annotation was designed to deal with different formats of dates in different fields, but as I said, there is no exception when an invalid format is entered.

Could someone suggest an elegant solution to this problem?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29

0 Answers0