如何基于OpenAPI规范使用openapi-generator生成LocalTime类型字段
可行实现方案如下
首先纠正你示例Schema中的小问题:对象的属性字段应该用properties而非parameters,parameters仅用于接口入参定义,修正后的Schema参考:
Visit: type: object properties: visitor: type: string timeOfVisit: type: string format: time
OpenAPI本身支持自定义format,所以该定义是合法的,只需要给openapi-generator补充自定义映射规则即可实现预期的生成效果,配置步骤如下:
步骤1:配置类型映射和导入映射
不管你用命令行、Maven插件还是Gradle插件调用openapi-generator,只需要新增两个配置项:
- 类型映射:将
type=string且format=time的字段映射为LocalTime类型,配置值为typeMappings=string+time=LocalTime - 导入映射:指定
LocalTime对应的导入包,如果你用Java8+内置时间类,配置值为importMappings=LocalTime=java.time.LocalTime;如果用Joda时间库,调整为对应Joda的包路径即可。
步骤2:可选序列化配置(按需添加)
如果需要生成的代码自带序列化注解适配Web框架,可以额外添加schema映射配置,比如适配Spring+Jackson的配置为:schemaMappings=time=@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.TIME)
同时在项目依赖中引入jackson-datatype-jsr310即可实现LocalTime的自动序列化/反序列化。
示例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> <configOptions> <dateLibrary>java8</dateLibrary> <typeMappings>string+time=LocalTime</typeMappings> <importMappings>LocalTime=java.time.LocalTime</importMappings> </configOptions> </configuration> </execution> </executions> </plugin>
配置完成后重新生成代码,就能得到你预期的LocalTime类型字段的效果。
内容的提问来源于stack exchange,提问作者Haf
相关产品推荐
相关产品推荐

