【问题标题】:return Enum's value instead of the name in Spring boot in API response在 API 响应中返回 Enum 的值而不是 Spring Boot 中的名称
【发布时间】:2020-04-12 23:23:05
【问题描述】:

我有一个枚举定义如下:

public enum IntervalType {
    HOUR(3600),
    DAY(3600*24),
    WEEK(3600*24*7),
    MONTH(3600*24*30);

    public Integer value;

    IntervalType() {}

    IntervalType(Integer value) {
        this.value = value;
    }

    @JsonValue
    public Integer toValue() {
        return this.value;
    }

    @JsonCreator
    public static IntervalType getEnumFromValue(String value) {
        for (IntervalType intervalType : IntervalType.values()) {
            if (intervalType.name().equals(value)) {
                return intervalType;
            }
        }
        throw new IllegalArgumentException();
    }

    @Override
    public String toString() {
        return this.name();
    }
}

我的响应类定义如下:

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class IntervalType {

    @JsonProperty("interval_type")
    @Enumerated(EnumType.STRING)
    private IntervalType intervalType;
}

我正在尝试使用响应实体从我的 Spring Boot 应用程序中返回它,它给出的是枚举的值而不是它的名称。

我需要做些什么来更改响应以使其具有名称而不是枚举的值?

【问题讨论】:

    标签: java rest api spring-boot enums


    【解决方案1】:

    你必须添加一个以值作为参数的构造函数:

    public enum IntervalType {
        HOUR(3600),
        DAY(3600*24),
        WEEK(3600*24*7),
        MONTH(3600*24*30);
    
        private int value;
    
        ...
    
        private IntervalType(int value) {
            this.value = value;
        }
    
        public int getValue() {
            return this.value;
        }
    }
    

    那么一般你这样称呼它:

    System.out.println(IntervalType.DAY.getValue()); // -> 86400
    System.out.println(IntervalType.DAY); // -> DAY
    

    【讨论】:

      【解决方案2】:

      如果您想要枚举的名称,请使用方法 name() 即:IntervalType.DAY.name()

       /**
       * Returns the name of this enum constant, exactly as declared in its
       * enum declaration.
       *
       * <b>Most programmers should use the {@link #toString} method in
       * preference to this one, as the toString method may return
       * a more user-friendly name.</b>  This method is designed primarily for
       * use in specialized situations where correctness depends on getting the
       * exact name, which will not vary from release to release.
       *
       * @return the name of this enum constant
       */
       public final String name() {
          return name;
       }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-22
        • 2021-08-26
        • 2018-02-19
        • 2020-06-25
        • 1970-01-01
        • 2022-01-23
        • 2021-04-25
        • 2021-02-20
        相关资源
        最近更新 更多