java - 为java对象设置OpenApi示例

标签 java spring-boot swagger openapi

我有一个 java 类,我想对其进行注释,以获得记录良好的 API。该类如下:

package test;

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "The Employee.", title = "Employee", type = "object")
public class Employee {

  @Schema(description = "Firstname.", example = "Alex", type = "string")
  private String firstname;

  @Schema(description = "The person.", type = "object")
  private Person person;

  public String getFirstname() {
      return firstname;
  }

  public Employee setFirstname(String firstname) {
      this.firstname = firstname;
      return this;
  }

  public Person getPerson() {
      return person;
  }

  public Employee setPerson(Person person) {
      this.person = person;
      return this;
  }
}

我在这里遇到的问题是,我似乎找不到一种方法来为属性 Person 设置示例。我尝试输入 json 字符串,但没有成功。是否有可能为对象树立榜样?谢谢。

这是我尝试过的:

...

  @Schema(description = "The person.", type = "object", example: "{'age': 30}")
  private Person person;

...

这会生成:

...

"example": "{'age': 30}"

...

但我正在寻找的是:

"example": {"age": 30}

最佳答案

要为 Employee 类中的 Person 对象设置 OpenAPI 示例,您可以使用 @Schema 注解。

import io.swagger.v3.oas.annotations.media.Schema;

@Schema(description = "The Employee.", title = "Employee", type = "object")
public class Employee {

  @Schema(description = "Firstname.", example = "Alex", type = "string")
  private String firstname;

  @Schema(description = "The person.", type = "object", example = "{ \"name\": \"John\", \"age\": 30 }")
  private Person person;

  public String getFirstname() {
      return firstname;
  }

  public Employee setFirstname(String firstname) {
      this.firstname = firstname;
      return this;
  }

  public Person getPerson() {
      return person;
  }

  public Employee setPerson(Person person) {
      this.person = person;
      return this;
  }
}

关于java - 为java对象设置OpenApi示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76780603/

相关文章:

java - 在 dropwizard 运行状况检查中禁用错误​​堆栈跟踪

java - QueryDSL:从实体构建查询

java - 由于相同的 bean,应用程序无法启动

Spring Boot - 自定义验证消息

swagger - 如何不在几乎所有路径中复制粘贴 3 个通用错误响应?

java - 从 Java 与 C++ 程序通信

java - setZone方法有问题吗?

java - Hibernate @Lob on byte[] 导致 "Bad value for type long"

google-app-engine - 从 Java Cloud Endpoint 生成 API 文档

c# - 将 swagger-ui 输出保存到文件