I am using LocalDateTime in the request body of my API in Spring.
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-mm-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime createdAt;
When I put an invalid date in request such as "2020-02-31 00:00:00" it is automatically converted to "2020-02-29 00:00:00". I want to throw Exception in case of an invalid date. It is mentioned in the official documentation that it converts to previous valid date .
In some cases, changing the specified field can cause the resulting date-time to become invalid,
such as changing the month from 31st January to February would make the day-of-month invalid.
In cases like this, the field is responsible for resolving the date.
Typically it will choose the previous valid date,
which would be the last valid day of February in this example.
You need to write a custom serializer for that.
class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("yyyy-mm-dd HH:mm:ss");
...
@Override
public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider)
throws IOException, JsonProcessingException {
// Do your validation using FORMATTER.
// Serialize the value using generator and provider.
}
}
Then you can just use it in your annotation.
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
Note that DateTimeFormatter throws an exception when formatting/parsing invalid values.
Check out the source of LocalDateTimeSerializer to know what has to be done. Check out Jackson Date - 10. Serialize Java 8 Date Without Any Extra Dependency for examples of writing a custom serializer. This is done analogous for a custom deserializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With