2

我正在使用 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 有自己的对象映射器,它覆盖了另一个对象映射器。知道如何解决它吗?

提前致谢

4

1 回答 1

0

如我所见,问题发生在SwaggerConfigurationextends WebMvcConfigurationSupport。如果不需要,可以删除此扩展程序。

于 2018-09-18T15:01:39.457 回答