根据 OpenAPI 规范生成 `LocalTime`

问题描述 投票:0回答:3

我看到OpenAPI中有一个

date
格式的字符串,并且通过使用
dateLibrary=java8
我们可以使用
LocalDate
生成
openapi-generator
字段。

但是有没有办法产生

LocalTime
字段呢? OpenAPI 中没有
time
格式,而
date-time
会生成
OffsetDateTime

编辑:很难提供一个可重现的例子,因为问题是关于我不能做的事情,但一些说明性的例子是我想要类似的东西:

架构规范:

Visit:
  type: object
  parameters:
    visitor:
      type: string
    timeOfVisit:
      type: string
      format: time

但显然 OpenAPI 规范中不存在

time
格式。生成的代码应该类似于

public class Visit {
  private String visitor;
  private LocalTime timeOfVisit;

  // Getters, setters, etc
}

肯定有某种方法可以让

openapi-generator
产生这个输出,不是吗?我发现有一些
import-mappings
LocalTime
映射到
org.joda.time.*
所以似乎有一种方法可以让它产生
LocalTime
类型,但我还没有找到它

java swagger openapi openapi-generator
3个回答
4
投票

解决了!实际上这很简单,但作为 OpenAPI 的初学者,很难找到解决方案。鉴于我问题中的示例,我只需运行

openapi-generator-cli
as

openapi-generator-cli generate -g java --type-mappings time=LocalTime

然后voilà,完成了!

编辑: 但这并不使用

java.time.LocalTime
作为类型,因为前面(在问题中)提到了
import-mappings
,所以最终的命令是:

openapi-generator-cli generate -g java --type-mappings time=LocalTime --import-mappings LocalTime=java.time.LocalTime

编辑:

另一种方法是在 pom.xml 中配置插件:

<configuration>
    <typeMappings>
        <typeMapping>time=LocalTime</typeMapping>
    </typeMappings>
    <importMappings>
        <importMapping>LocalTime=java.time.LocalDateTime</importMapping>
    </importMappings>
</configuration>

2
投票

我发现pom.xml中的configOptions标签中有一个dateLibrary选项。这样我就不必在 OffsetDateTime (最初生成)和 LocalDateTime 之间手动映射。

如果将 true 添加到配置标签,它将打印出所有选项。

dateLibrary
        Option. Date library to use (Default: threetenbp)
            joda - Joda (for legacy app only)
            legacy - Legacy java.util.Date (if you really have a good reason not to use threetenbp
            java8-localdatetime - Java 8 using LocalDateTime (for legacy app only)
            java8 - Java 8 native JSR310 (preferred for jdk 1.8+) - note: this also sets "java8" to true
            threetenbp - Backport of JSR310 (preferred for jdk < 1.8)

2
投票

如果您将 spring 与 gradle 结合使用,则需要将这两个属性添加到 build.gradle

openApiGenerate() {
    generatorName = "spring"
    ...
    typeMappings = ["time": "LocalTime"]
    importMappings = ["LocalTime": "java.time.LocalTime"]
}

所以这个配置会说

format: time
会生成
LocalTime
类型,
java.time.LocalTime
这里是这个类型的来源。

© www.soinside.com 2019 - 2024. All rights reserved.