简体   繁体   中英

return Enum's value instead of the name in Spring boot in API response

I have an enum defined like:

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();
    }
}

And my response class is defined as below:

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

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

I am trying to return this from my spring boot application with a Response entity and the it is giving enum's value instead of it's name.

What do I need to do to change the response to have it's name and not value of the enum?

You have to add a constructor with the value as parameter:

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;
    }
}

Then in general you call it like this:

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

If you want the name of the enum use the the method name() ie: 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;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM