在 API 响应中返回 Num 的值而不是 Spring 启动中的名称



>我有一个枚举定义如下:

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 启动应用程序中返回它,并且它给出了枚举的值而不是它的名称。

我需要做什么才能将响应更改为具有枚举的名称而不是值?

您必须添加一个构造函数,并将值作为参数:

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

如果你想要枚举的名称,请使用方法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;
}

最新更新