如何在使用Spring Boot的RESTful服务中返回String Enum的值?

huangapple go评论64阅读模式
英文:

How do I return a String Enum's value from a RESTful service using Spring Boot?

问题

这段代码中的问题是它返回了枚举值而不是字符串值。您可以尝试在控制器中使用枚举值的 getResult() 方法来获取字符串值,然后返回该字符串值。这将确保您得到的是字符串值而不是枚举值。例如:

// 在控制器中使用 getResult() 方法获取字符串值
String resultString = resultEnum.getResult();

// 然后返回 resultString

这样,在控制器中返回的将会是字符串值,而不是枚举值。

英文:

I have an enum that contains only three values, including one with spaces:

public enum ResultEnum {
	Sold("Sold"),
	No_deal_today("No deal today"),
	Appointment("Appointment");
	
	private String result;
	
	private ResultEnum(String result) {
		this.result = result;
	}
	
	public String getResult() {
		return result;
	}
	
	public static ResultEnum fromResult(String result) {
		switch (result) {
        case "Sold":
            return ResultEnum.Sold;
 
        case "No deal today":
            return ResultEnum.No_deal_today;
 
        case "Appointment":
            return ResultEnum.Appointment;
 
        default:
            throw new IllegalArgumentException("ResultEnum [" + result
                    + "] not supported.");
        }
	}
}

I created a converter for it:

@Converter(autoApply = true)
public class ResultConverter implements AttributeConverter<ResultEnum, String> {

	@Override
	public String convertToDatabaseColumn(ResultEnum resultEnum) {
		return resultEnum.getResult();
	}

	@Override
	public ResultEnum convertToEntityAttribute(String result) {
		return ResultEnum.fromResult(result);
	}

}

This works great, except that it returns the Enum value in the results:

"result": "No_deal_today"

Is there a way to return the string value from the controller rather than the ENUM value?

"result": "No deal today"

Thanks!

答案1

得分: 2

只需将@JsonValue注解添加到getResult()方法中:

@JsonValue
public String getResult() {
    return result;
}
英文:

All I had to do was add the @JsonValue annotation to getResult():

@JsonValue
public String getResult() {
	return result;
}

huangapple
  • 本文由 发表于 2023年5月31日 22:54:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76374807.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定