简体   繁体   English

如何在 Swagger 中指定不区分大小写的枚举?

[英]How can I specify a case-insensitive enum in Swagger?

I have an enum in Java and I want to use it as parameter in a GET request in my REST API - where the swagger docs are generated from annotations in the Java controller. I have an enum in Java and I want to use it as parameter in a GET request in my REST API - where the swagger docs are generated from annotations in the Java controller.

The enum itself has the ability to use case-insensitive values, but is defined with upper case values per Java conventions.枚举本身能够使用不区分大小写的值,但根据 Java 约定使用大写值定义。

public enum SortDirection {

  ASC, DESC;

  public static SortDirection fromString(String value) { 
    try {
      return SortDirection.valueOf(value.toUpperCase(Locale.US));
    } catch(Exception e) {
      throw new IllegalArgumentException("Invalid value " + value + ". Valid values are 'asc' or 'desc' (case insensitive).", e);
    }
  }
}

The fromString allows lower case to be passed as a valid option as it is more common for URLs to use lower case. fromString允许将小写字母作为有效选项传递,因为 URL 使用小写字母更为常见。

If I use a default value of asc swagger will throw a validation error:如果我使用默认值asc swagger 将引发验证错误:

Default values must be present in enum默认值必须存在于enum

How can I specify that both lowercase and uppercase are valid options and set a default value of asc ?如何指定小写和大写都是有效选项并设置默认值asc

You can try using io.swagger.annotations.ApiParam in method signature:您可以尝试在方法签名中使用 io.swagger.annotations.ApiParam :

public void controllerMethod(
       @ApiParam(allowableValues="asc,desc") @RequestParam SortDirection sortDirection);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM