【问题标题】:Conflict between Swagger2 and jackson-datatype-jsr310 in Spring Boot applicationSpring Boot 应用程序中 Swagger2 和 jackson-datatype-jsr310 之间的冲突
【发布时间】:2019-01-09 05:07:21
【问题描述】:

我正在使用 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>

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

这是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】:

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

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 2016-11-14
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      相关资源
      最近更新 更多