FasterXML / jackson-modules-java8

Set of support modules for Java 8 datatypes (Optionals, date/time) and features (parameter names)
Apache License 2.0
399 stars 116 forks source link

Does Jackson work with Spring's @DateTimeFormat? #218

Closed dsgoers closed 3 years ago

dsgoers commented 3 years ago

Hi, I have an entity like this:

public class Entity {

    @DateTimeFormat(pattern = "MM/dd/yyyy")
    private LocalDate dateOfBirth;
}

and the method I'm POSTing to is:

    @RequestMapping(value = "register", method = POST)
    public ResponseEntity<Void> register(@RequestBody final Entity entity) {...

However, I'm seeing this error:

JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String "05/18/2021": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '05/18/2021' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String "05/18/2021": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '05/18/2021' could not be parsed at index 0

It looks like @DateTimeFormat doesn't get used. I can fix this by adding @JsonFormat, but I was wondering if I needed to. For some background, this entity is used in another request that's an HTML form POST (ie not Jackson) so that's why @JsonFormat was never used.

Thanks.

cowtowncoder commented 3 years ago

No, Jackson does not depend on any Spring components by default.

It should be quite easy to write a simple AnnotationIntrospector that did this, however; and it could form a new small module. AnnotationIntrospector has a method called to look for format information; JacksonAnnotationIntrospector looks for its own @JsonFormat but custom one can use whatever source.

The reason this would have to go in a separate module is to keep Jackson components as close to zero-(external-)dependency as possible: users can then pick and choose things they depend on.