英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论