cod*_*l94 1 java api rest enums 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)
我试图用一个响应实体从我的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后通常你会这样称呼它:
System.out.println(IntervalType.DAY.getValue()); // -> 86400
System.out.println(IntervalType.DAY); // -> DAY
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2063 次 |
| 最近记录: |