如何在 Kotlin 中使用 Swagger @ApiResponses注释?

2022-09-02 13:04:08

如何将以下 Swagger 注释从 Java 转换为 Kotlin?

 @ApiResponses(value = { @ApiResponse(code = 200, message = "Given admin user found"),
            @ApiResponse(code = 404, message = "..."),
            @ApiResponse(code = 500, message = "..."),
            @ApiResponse(code = 400, message = "..."),
            @ApiResponse(code = 412, message = "...") })

这不起作用:

@ApiResponses(value = listOf( 
        ApiResponse(code = 200, message = "..."),
        ApiResponse(code = 404, message = "..."),
        ApiResponse(code = 500, message = "..."),
        ApiResponse(code = 400, message = "..."),
        ApiResponse(code = 412, message = "...") ))

错误是:

类型推断失败。预期类型不匹配:推断的类型为 List,但 API 响应是预期的

当我只使用一个而不是时,它可以工作,但我必须定义更多。@ApiResponselistOf()@ApiResponse(s)

我使用 Swagger 2.5.0


答案 1

Kotlin 语言参考中所述:

如果 Java 中的 value 参数 [of an Annotation] 具有数组类型,则它将成为 Kotlin 中的 vararg 参数。

因此,为了使您的示例起作用,您需要这样说:

@ApiResponses(
    ApiResponse(code = 200, message = "..."),
    ApiResponse(code = 404, message = "..."),
    ApiResponse(code = 500, message = "..."),
    ApiResponse(code = 400, message = "..."),
    ApiResponse(code = 412, message = "...")
)

答案 2

对于Swagger 3来说,这是要走的路:

 @ApiResponses(value = [
    ApiResponse(responseCode = "200", description = "...", content = [
        (Content(mediaType = "application/json", array = (
        ArraySchema(schema = Schema(implementation = DataModel::class)))))]),
    ApiResponse(responseCode = "400", description = "...", content = [Content()]),
    ApiResponse(responseCode = "404", description = "...", content = [Content()])]
    )

此代码段还包括 和 注释示例。@Content@ArraySchema@Schema


推荐