微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

springdoc-openapi 如何显示字符串数组作为响应

如何解决springdoc-openapi 如何显示字符串数组作为响应

网络上没有关于如何使用 springdocs-openapi 库 (1.5.7) 获取以下输出的好示例。我希望获得以下输出

[
  "A","B","C"
]

这是基于所提供示例的代码

@Operation(summary = "")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200",description = "OK",content = {@Content(mediaType = "application/json",array = @ArraySchema(schema = @Schema(implementation = String.class)),examples = {@ExampleObject("A"),@ExampleObject("B"),@ExampleObject("C")}
                    )})

结果如下

[
  "string"
]

上面列出的输出 ["A","C"] 如何通过 springdocs-openapi 库实现?

解决方法

您错误地使用了 @ExampleObjectvalue 属性(如果您未指定任何内容,也是默认属性)采用示例负载的 JSON 序列化对象。

因此要获得["A","B"],您不需要多个@ExampleObject,而是需要一个示例的一个注释。

因此更新如下所示的代码应该会有所帮助

@Operation(summary = "Some method")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200",description = "OK",content = {
        @Content(
            mediaType = MediaType.APPLICATION_JSON_VALUE,array = @ArraySchema(schema = @Schema(implementation = String.class)),examples = {
                @ExampleObject("[\"A\",\"B\"]")
            }
        )
    })
})

下图是上面代码的输出

要指定多个示例,应该有多个示例对象,如下所示

@Operation(summary = "Some method")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200",examples = {
                @ExampleObject(name = "Example 1",summary = "Summary 1",description = "Some desc",value = "[\"A\",\"B\"]"),@ExampleObject(name = "Example 2",summary = "Summary 2",value = "[\"C\",\"D\"]")
            }
        )
    })
})

注意name@ExampleObject 属性用于在规范文件内部标识示例。

"responses": {
  "200": {
    "description": "OK","content": {
      "application/json": {
        "schema": {
          "type": "array","items": {
            "type": "string"
          }
        },"examples": {
          "Example 1": {
            "summary": "Summary 1","description": "Some desc","value": [
              "A","B"
            ]
          },"Example 2": {
            "summary": "Summary 2","value": [
              "C","D"
            ]
          }
        }
      }
    }
  }
}

输出如下图 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。