如何为Kotlin数据类中的属性设置OpenAPI类型/模式

在使用Kotlin的microprofile / Quarkus项目中,数据类的变量类型为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

我已经尝试对数据类进行注释,以使用实现字符串和类型字符串,但是它不会改变任何内容。

@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
)
to71229 回答:如何为Kotlin数据类中的属性设置OpenAPI类型/模式

问题在于数据类会得到一些特殊待遇,并且您的注释会放在构造函数参数上。

您可以在生成的数据类字节码中看到这一点。相关代码段:

@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;
   }

   // ...
}
本文链接:https://www.f2er.com/2653038.html

大家都在问