如何强制OpenAPI Generator生成UTC格式的date类型示例?
问题分析
你遇到的问题根源在于pom.xml里的OffsetDateTime=LocalDateTime类型映射,导致OpenAPI Generator错误地将date格式的字段按date-time逻辑处理,再加上开发者本地时区差异,生成的ApiModelProperty示例就变成了带时区的完整日期时间格式。
解决方案
1. 给OpenAPI Generator添加全局日期配置
在你的pom.xml的OpenAPI Generator插件配置中,新增configOptions,强制date类型使用UTC时区和指定格式:
<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <!-- 确保插件版本为6.x及以上 --> <version>6.6.0</version> <executions> <!-- 你的执行配置 --> </executions> <configuration> <!-- 原有typeMappings和importMappings保留 --> <typeMappings> <typeMapping>OffsetDateTime=LocalDateTime</typeMapping> </typeMappings> <importMappings> <importMapping>java.time.OffsetDateTime=java.time.LocalDateTime</importMapping> </importMappings> <!-- 添加以下配置 --> <configOptions> <datePattern>yyyy-MM-dd</datePattern> <timezone>UTC</timezone> <dateLibrary>java8</dateLibrary> </configOptions> </configuration> </plugin>
datePattern指定date类型的输出格式为yyyy-MM-dd,和你规范里的示例格式一致timezone强制使用UTC时区,避免本地时区影响dateLibrary指定用Java 8日期API,确保类型映射和格式化逻辑兼容
2. 保持OpenAPI规范中的示例格式
规范里的ExpiryDate示例继续使用纯日期格式,不要添加时间或时区:
ExpiryDate: type: string example: "2024-10-23" format: date
之前尝试带时区的示例无效,是因为生成器会解析该示例后按配置的时区重新格式化,反而破坏了纯date的格式。
3. 验证插件版本
如果使用的是旧版本OpenAPI Generator(比如5.x及以下),可能存在date类型处理的bug,建议升级到6.x或更高版本,确保配置能生效。
内容的提问来源于stack exchange,提问作者Ramji
相关产品推荐
相关产品推荐

