Swagger中LocalDateTime类型的正确实现方案咨询
解决方案
要让Swagger契约生成的DTO中createdDate字段类型为LocalDateTime而非默认的OffsetDateTime,可以通过自定义格式定义+代码生成器映射或者注解指定两种方式实现,具体如下:
方式一:OpenAPI 3.x契约配置 + 代码生成器映射
1. 修改Swagger契约定义
将字段的format从默认的date-time改为自定义的local-date-time,明确表示这是无时区的日期时间类型:
createdDate: type: string format: local-date-time example: 2017-01-13T17:09:42.411
2. 配置代码生成器映射
如果使用OpenAPI Generator生成Java代码,需要添加类型映射规则,让生成器将local-date-time格式映射为java.time.LocalDateTime:
Maven插件配置示例
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <!-- 使用最新稳定版本 --> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${project.basedir}/src/main/resources/openapi.yaml</inputSpec> <generatorName>spring</generatorName> <!-- 映射自定义格式到LocalDateTime --> <typeMappings> <typeMapping>local-date-time=LocalDateTime</typeMapping> </typeMappings> <!-- 指定LocalDateTime的全类名导入 --> <importMappings> <importMapping>LocalDateTime=java.time.LocalDateTime</importMapping> </importMappings> </configuration> </execution> </executions> </plugin>
命令行生成示例
openapi-generator generate -i openapi.yaml -g spring \ --type-mappings local-date-time=LocalDateTime \ --import-mappings LocalDateTime=java.time.LocalDateTime
方式二:Springfox Swagger 2 注解指定(代码优先场景)
如果是代码优先的开发模式(先写Java代码再生成Swagger文档),可以直接在DTO字段上使用@Schema注解指定格式和类型:
import io.swagger.v3.oas.annotations.media.Schema; import java.time.LocalDateTime; public class YourDto { @Schema( type = "string", format = "local-date-time", example = "2017-01-13T17:09:42.411" ) private LocalDateTime createdDate; // getter、setter方法 }
补充:Jackson序列化配置
为了确保LocalDateTime在接口请求/响应中能正确序列化和反序列化,需要在Spring Boot中添加Jackson的相关依赖和配置:
<!-- 引入Jackson对Java 8时间类型的支持 --> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
在application.yml中配置序列化格式:
spring: jackson: serialization: write-dates-as-timestamps: false deserialization: adjust-dates-to-context-time-zone: false date-format: "yyyy-MM-dd'T'HH:mm:ss.SSS"
内容的提问来源于stack exchange,提问作者Keerthi
相关产品推荐
相关产品推荐

