Skip to content
Advertisement

How do I globally enable “strict” handling of LocalDate values using Jackson?

Jackson Java 8 Date/time module issue jackson-modules-java8#212 mentions enabling “strict” handling via a global default:

Currently LocalDateDeserializer automatically accepts non-standard format where time part also exists. While this is useful for some use cases, compatibility, it seems reasonable that if user forces “strict” handling (via @JsonFormat, or global default), that part would not be accepted.

However, I am completely failing at figuring out how to enable this globally. I’ve checked configuration classes such as DeserializationFeature and done Internet & Stack Overflow searches for this, but have not come up with an answer.

How can I enable “strict” handling of LocalDate, such that @JsonFormat behaves the same as @JsonFormat(lenient = OptBoolean.FALSE) for values deserialized by Jackson?

Advertisement

Answer

You can set global leniency by com.fasterxml.jackson.databind.ObjectMapper#setDefaultLeniency.

But this won’t fail when LocalDate contains the time part too. Since there is strange logic in com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer. It uses DateTimeFormatter ISO_LOCAL_TIME as default formatter, which doesn’t allow time part, but when deserializer parses datetime, this code runs:

JavaScript

You can avoid this by duplicating default DateTimeFormatter. Here is my proposal for this:

JavaScript

Jackson databind 2.13

As for version 2.13 of JavaTime module, lenient check was added for disallowing time part in LocalDate. So workaround with a copy of DateTimeFormatter is not needed, setDefaultLeniency(false) should be enough.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement