Conflict between Swagger2 and jackson-datatype-jsr310 in Spring Boot application

830 Views Asked by At

I am creating a REST API using Spring Boot and have issues serialising LocalDateTime when I use Swagger 2.

Without Swagger the JSON output is like this:

{
    "id": 1,
    ...
    "creationTimestamp": "2018-08-01T15:39:09.819"
}

And with Swagger it is like this:

{
    "id": 1,
    ...
    "creationTimestamp": [
        2018,
        8,
        1,
        15,
        40,
        59,
        438000000
    ]
}

I have added this to the pom file so the dates are serialised correctly:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
   </dependency>

This is the configuration of Jackson:

@Configuration
public class JacksonConfiguration {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {

        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        return objectMapper;
    }
}

And this is the configuration of Swagger:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebMvcConfigurationSupport {

    @Bean
    public Docket messageApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xxx.message.controller"))
                .build()
                .apiInfo(metaData());
    }

    private ApiInfo metaData() {

        return new ApiInfoBuilder()
                .title("Message service")
                .version("1.0.0")
                .build();
    }

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

It works when I add add like this a deserialiser to the fields of the DTO. However it should work without having to add it.

@JsonFormat(pattern = "dd/MM/yyyy")
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonSerialize(using = LocalDateTimeSerializer.class)
private LocalDateTime creationTimestamp;

I guess that the problem is that Swagger has its own object mapper that is overriding the other. Any idea of how to solve it?

Thanks in advance

1

There are 1 best solutions below

0
On

As I see, the problem occurs when SwaggerConfiguration extends WebMvcConfigurationSupport. You can remove this extension if you don't need it.