ARTICLE AD BOX
Related: Flaky external API, unresponsive owner
Is there an elegant way to make it more flexible so that a Date is successfully parsed regardless of whether it's yyyy-MM-dd hh:mm:ss or yyyy-MM-dd?
Preferrably, without trying multiple formats and swallowing exceptions.
import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; public class DateTimeFormatDeserializer extends JsonDeserializer<Date>{ @Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { if (jp.getCurrentToken() == JsonToken.VALUE_STRING) { String str = jp.getText().trim(); if (str.length() == 0) { return null; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date date = sdf.parse(str); return date; } catch (ParseException e) { throw new RuntimeException("Cannot convert string '" + str +"' to Date (yyyy-MM-dd HH:mm:ss)"); } } return null; } }Java 8, Jackson 2.13.2.2, Spring 5.3.18.
