Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 696
coderahul94 Avatar asked Sep 06 '25 03:09

coderahul94


1 Answers

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
like image 195
Svilen Yanovski Avatar answered Sep 07 '25 17:09

Svilen Yanovski