Swagger架构未显示枚举的自定义值。

huangapple go评论67阅读模式
英文:

Swagger schema not showing custom value of enum

问题

{
  "enum": ["DOG", "CAT"]
}
英文:

I have created an enum which also stores a value

import com.fasterxml.jackson.annotation.JsonValue;

public enum AnimalType {
  DOG("dog"),
  CAT("cat"),

  private final String displayName;

  AnimalType(String displayName) {
    this.displayName = displayName;
  }

  @JsonValue
  public String getDisplayName() {
    return displayName;
  }

  @Override
  public String toString() {
    return displayName;
  }
}

I am creating enum in this way because the user will give me input dog or cat. The enum value is getting serialized and deserialized properly.

But the swagger.json is showing DOG and CAT in place of dog and cat. I don't want the user to see the internal enum name and since the schema will be used by the users, I want to display the dog or cat in the schema.

        "type" : {
          "type" : "string",
          "enum" : [ "DOG", "CAT"]
        },

I have tried using @JsonProperty annotation( like @JsonProperty("dog")), but that didn't solve the problem. Can you please guide me on how I can solve this problem?

Versions:
swagger: 2.0
jackson: 2.7.9

答案1

得分: 1

Test your code with

@JsonCreator
public static AnimalType fromString(String key) {
    return displayName == null
            ? null
            : AnimalType.valueOf(key.toUpperCase());
}
英文:

Test your code with

@JsonCreator
public static AnimalType fromString(String key) {
    return displayName == null
            ? null
            : AnimalType.valueOf(key.toUpperCase());
}

答案2

得分: 0

我尝试了各种替代方法来使其工作,例如

public enum AnimalType {
  @JsonProperty("dog") DOG("dog"),
  @JsonProperty("cat") CAT("cat"),

或者使用 @JsonCreator,如 @sercheo_87 建议的。但是模式没有显示所需的值。

我发现这是 swagger-core 中的一个错误。使用更新的 swagger 版本帮助了我。同时,他们也在将这些更改回溯到这个版本。

英文:

I tried various alternatives to make it work such as

public enum AnimalType {
  @JsonProperty("dog") DOG("dog"),
  @JsonProperty("cat") CAT("cat"),

or using @JsonCreator as suggested by @sercheo_87. But the schema was not showing the required value.

I found out that it is a bug in swagger-core. Taking a updated version of swagger helped me. Also they are backporting the changes to this version.

huangapple
  • 本文由 发表于 2020年8月11日 01:29:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63345141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定