简体   繁体   中英

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.

The enum itself has the ability to use case-insensitive values, but is defined with upper case values per Java conventions.

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.

If I use a default value of asc swagger will throw a validation error:

Default values must be present in enum

How can I specify that both lowercase and uppercase are valid options and set a default value of asc ?

You can try using io.swagger.annotations.ApiParam in method signature:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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