2

I'm working on a Spring WebMvc (not Spring Boot) project that uses pure Java configuration for setting up its beans. I am having difficulty getting Spring/Jackson to respect the @DateTimeFormat annotation with java.time (jsr310) objects such as LocalDateTime.

I have both jackson-datatype-jsr310 and jackson-databind jars (version 2.7.4) on the classpath, along with the relevant spring jars for a basic webmvc application spring-context and spring-webmvc (version 4.3.0.RELEASE)

Here is my relevant configuration class:

@Configuration
@ComponentScan({"com.example.myapp"})
public class WebAppConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper mapper = Jackson2ObjectMapperBuilder
            .json()
            .indentOutput(true)
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .findModulesViaServiceLoader(true)
            .build();

        converters.add(new MappingJackson2HttpMessageConverter(mapper));

        super.addDefaultHttpMessageConverters(converters);
    }
}

I've tested this with serializing my data models over a rest controller. Appears that Jackson is respecting @JsonFormat, but completely ignoring @DateTimeFormat.

What additional configuration am I missing to get spring/jackson to respect @DateTimeFormat? Are there any key differences between the two annotations that I should be aware of, problems that I could run into just by using @JsonFormat?

Alex
  • 392
  • 4
  • 17

1 Answers1

3

@JsonFormat is a Jackson annotation; @DateTimeFormat is a Spring annotation.

@JsonFormat will control formatting during serialization of LocalDateTime to JSON.

Jackson doesn't know about Spring's @DateTimeFormat, which is used to control formatting of a bean in Spring when it's rendered in the JSP view.

Javadocs:

http://docs.spring.io/spring-framework/docs/4.2.3.RELEASE/javadoc-api/org/springframework/format/annotation/DateTimeFormat.html

http://static.javadoc.io/com.fasterxml.jackson.core/jackson-annotations/2.7.5/com/fasterxml/jackson/annotation/JsonFormat.html

Ron
  • 254
  • 2
  • 17
ck1
  • 5,243
  • 1
  • 21
  • 25
  • 1
    Think I was mostly getting confused looking at examples online since (correct me if I'm wrong) that means there are scenarios in which I could potentially need to use both annotations on java time properties. For instance, if I wished to expose one bean both via rest (with Jackson) and as a spring formatted string on a jsp page. – Alex Jun 17 '16 at 22:00
  • Correct @Alex, you might need to use both. – ck1 Jun 17 '16 at 23:42