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

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

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

问题

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

  1. // 在控制器中使用 getResult() 方法获取字符串值
  2. String resultString = resultEnum.getResult();
  3. // 然后返回 resultString

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

英文:

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

  1. public enum ResultEnum {
  2. Sold("Sold"),
  3. No_deal_today("No deal today"),
  4. Appointment("Appointment");
  5. private String result;
  6. private ResultEnum(String result) {
  7. this.result = result;
  8. }
  9. public String getResult() {
  10. return result;
  11. }
  12. public static ResultEnum fromResult(String result) {
  13. switch (result) {
  14. case "Sold":
  15. return ResultEnum.Sold;
  16. case "No deal today":
  17. return ResultEnum.No_deal_today;
  18. case "Appointment":
  19. return ResultEnum.Appointment;
  20. default:
  21. throw new IllegalArgumentException("ResultEnum [" + result
  22. + "] not supported.");
  23. }
  24. }
  25. }

I created a converter for it:

  1. @Converter(autoApply = true)
  2. public class ResultConverter implements AttributeConverter<ResultEnum, String> {
  3. @Override
  4. public String convertToDatabaseColumn(ResultEnum resultEnum) {
  5. return resultEnum.getResult();
  6. }
  7. @Override
  8. public ResultEnum convertToEntityAttribute(String result) {
  9. return ResultEnum.fromResult(result);
  10. }
  11. }

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

  1. "result": "No_deal_today"

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

  1. "result": "No deal today"

Thanks!

答案1

得分: 2

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

  1. @JsonValue
  2. public String getResult() {
  3. return result;
  4. }
英文:

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

  1. @JsonValue
  2. public String getResult() {
  3. return result;
  4. }

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:

确定