从OpenAPI规范生成`LocalTime`

4
我看到在OpenAPI中有一个针对字符串的date格式,通过使用dateLibrary=java8,我们可以使用openapi-generator生成LocalDate字段。

但是有没有办法生成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-mappingsLocalTime映射到org.joda.time.*,因此似乎有一种方法可以生成LocalTime类型,但我还没有找到它。


你可以使用 OffsetDateTime 并调用 myOffsetDateTime.toLocalTime() - deHaar
1
它可能能够工作,但并不是非常有效。首先,我需要在许多不同的地方进行设置。其次,在OpenAPI规范中将参数设置为“日期时间”会传达它允许任何日期和时间的组合,而实际上它只适用于时间。我想我的措辞不太好,因为我希望在我的API和生成的代码中都有一个时间参数。(也许使用字符串的正则表达式模式是我的唯一选择?) - Haf
抱歉,我认为问题不在于措辞,而是缺少示例值和代码。您能否提供一些最小化且可重现的情况示例? - deHaar
我已经添加了一个小例子,说明我需要什么。 - Haf
3个回答

4
解决了!实际上很简单,但作为OpenAPI的初学者,找到解决方案还是有一定难度的。根据我提出问题中的示例,我只需要运行以下命令:openapi-generator-cli generate -g java --type-mappings time=LocalTime,然后就完成了!
编辑:但是,由于之前在问题中提到的import-mappings,这并没有使用java.time.LocalTime作为类型,所以最终的命令应该是:
openapi-generator-cli generate -g java --type-mappings time=LocalTime --import-mappings LocalTime=java.time.LocalTime

好的,很好...因为规范只包括你已经提到的两种类型:date-timedate... - deHaar
1
有没有一种方法可以使用 openapi-generator-maven-plugin 来完成相同的事情? - Ghassen
4
是的,在您的 pom.xml 文件的 <configuration>...</configuration> 块中使用以下代码片段: OffsetDateTime=java.time.LocalDateTime java.time.OffsetDateTime=java.time.LocalDateTime 抱歉格式不太好。在 typeMapping 中,您可能还需要完全限定 OffsetDateTime,但这对我有效。 - Haf

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)

1
如果您正在使用Gradle的Spring,则需要将以下两个属性添加到build.gradle文件中。
openApiGenerate() {
    generatorName = "spring"
    ...
    typeMappings = ["time": "LocalTime"]
    importMappings = ["LocalTime": "java.time.LocalTime"]
}

因此,这个配置将说明format: time将生成LocalTime类型,并且java.time.LocalTime是该类型的源。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接