Alex
Alex

Reputation: 402

Spring DateTimeFormat Configuration for java.time

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?

Upvotes: 2

Views: 4890

Answers (1)

ck1
ck1

Reputation: 5443

@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

Upvotes: 3

Related Questions