Spring Boot应用程序中Swagger2和jackson-datatype-jsr310之间的冲突

问题描述 投票:0回答:1

我正在使用Spring Boot创建REST API,并且在使用Swagger 2时会出现序列化LocalDateTime的问题。

没有Swagger,JSON输出是这样的:

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

而Swagger则是这样的:

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

我已将此添加到pom文件中,因此日期序列化正确:

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

这是杰克逊的配置:

@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;
    }
}

这是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/");
    }
}

当我向DTO的字段添加像这样的反序列化器时,它可以工作。但是它应该工作而不必添加它。

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

我想问题是Swagger有自己的对象映射器覆盖另一个。怎么解决它的想法?

提前致谢

spring-boot swagger-2.0 jsr310
1个回答
0
投票

正如我所看到的,当SwaggerConfiguration扩展WebMvcConfigurationSupport时会出现问题。如果您不需要,可以删除此扩展程序。

© www.soinside.com 2019 - 2024. All rights reserved.