Java 如何让 Swagger UI 的参数成为下拉菜单而不是文本输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24398653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:59:15  来源:igfitidea点击:

How to get Swagger UI's Parameter to be Dropdown menu instead of Text Input

javarestjerseyswagger

提问by mirage1s7

I am using swagger to display my RESTApi, one parameter of an API takes string as input and convert it to enum value. Is there any way to display a drop-down menu on the Swagger UI instead of having a text input field so that users can only select the string values within the enum value.

我正在使用 swagger 来显示我的 RESTApi,API 的一个参数将字符串作为输入并将其转换为枚举值。有什么方法可以在 Swagger UI 上显示下拉菜单而不是文本输入字段,以便用户只能选择枚举值中的字符串值。

采纳答案by localhost

The key is to use allowableValuesin the @ApiParamannotation.

关键是allowableValues@ApiParam注解中使用。

The demo showing the result:

显示结果的演示:

http://petstore.swagger.io/#!/pet/findPetsByStatus

http://petstore.swagger.io/#!/pet/findPetsByStatus

Check out pet/findByStatus, it's not a dropdown but input is limited in the multi-select box.

查看pet/findByStatus,它不是下拉列表,但多选框中的输入受到限制。

回答by Kundan

you can display dropdown using following code of swagger. You have to use enum. e.g. if you want to take gender as input then there can be three possible values

您可以使用以下 swagger 代码显示下拉列表。你必须使用enum。例如,如果您想将性别作为输入,则可以有三个可能的值

  • male, female, other
  • 男、女、其他
-name: "gender"
          in: "query"
          type: "string"
          enum: [ "male", "female", "other"]
          description: "Enter user gender here."
          required: true

回答by Sagar Vaghela

You can directly use enum instead of String parameter as a API parameter.

您可以直接使用 enum 而不是 String 参数作为 API 参数。

@RequestMapping(value = "/test", method = RequestMethod.POST)
public void test(EnumTest enum) {
    // body
}

EnumTest.java

枚举测试

public enum EnumTest {

    One("One"),
    Two("Two");

    private String str;

    EnumTest(String str){
       this.str = str;
    }

    public String getStr() {
       return str;
    }

}

}