如何为 Kotlin 数据 class 中的 属性 设置 OpenAPI type/schema

How to set the OpenAPI type/schema for a property in a Kotlin data class

在使用 Kotlin 的 Microprofile / Quarkus 项目中有一个数据 class 和一个 Instant 类型的变量。

@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    var time: Instant = Instant.EPOCH
)

问题是生成的 openapi 模式不代表 Instant 值的实际传输方式。

模式如下所示,而它只是表示为这样的字符串:2015-06-02T21:34:33.616Z.

Instant:
  type: object
  properties:
    nanos:
      format: int32
      type: integer
    seconds:
      format: int64
      type: integer
    epochSecond:
      format: int64
      type: integer
    nano:
      format: int32
      type: integer

我已经尝试注释数据 class 以使用实现字符串和类型字符串,但它没有改变任何东西。

@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    @Schema(implementation = String::class, type = SchemaType.STRING)
    var time: Instant = Instant.EPOCH
)

问题是数据 classes 得到了一些特殊处理,并且您的注释放在 构造函数参数 .

您可以在数据 class 的生成 Java 代码中看到这一点。相关片段:

@Schema(
   name = "Vehicle",
   description = "POJO that represents a vehicle at a specific time."
)
@Metadata(...)
public final class VehicleDTO {
   @NotNull
   private Instant time;

   @NotNull
   public final Instant getTime() {
      return this.time;
   }

   public final void setTime(@NotNull Instant var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.time = var1;
   }

   public VehicleDTO(@Schema(implementation = String.class,type = SchemaType.STRING) @NotNull Instant time) {
      Intrinsics.checkParameterIsNotNull(time, "time");
      super();
      this.time = time;
   }

   // ...
}

您需要告诉 Kotlin 使用 use-site target:

将其放在场上
@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    @field:Schema(implementation = String::class, type = SchemaType.STRING)
    var time: Instant = Instant.EPOCH
)

之后的相关代码:

@Schema(
   name = "Vehicle",
   description = "POJO that represents a vehicle at a specific time."
)
@Metadata(...)
public final class VehicleDTO {
   @Schema(
      implementation = String.class,
      type = SchemaType.STRING
   )
   @NotNull
   private Instant time;

   @NotNull
   public final Instant getTime() {
      return this.time;
   }

   public final void setTime(@NotNull Instant var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.time = var1;
   }

   public VehicleDTO(@NotNull Instant time) {
      Intrinsics.checkParameterIsNotNull(time, "time");
      super();
      this.time = time;
   }

   // ...
}