小编cod*_*l94的帖子

在 API 响应中返回 Enum 的值而不是 Spring boot 中的名称

我有一个枚举定义如下:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的响应类定义如下:

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

    @JsonProperty("interval_type")
    @Enumerated(EnumType.STRING)
    private IntervalType intervalType;
} …
Run Code Online (Sandbox Code Playgroud)

java api rest enums spring-boot

1
推荐指数
1
解决办法
2063
查看次数

标签 统计

api ×1

enums ×1

java ×1

rest ×1

spring-boot ×1