简体   繁体   English

如何将枚举值附加到 object,而不是枚举名称?

[英]How do I attach the enum value to an object, instead of the enum name?

So my title is probably not the best one, but I think I can better show it in code what I want to achieve.所以我的标题可能不是最好的,但我认为我可以更好地在代码中显示我想要实现的目标。 I'm doing things with Spring Boot, JPA and React.我正在使用 Spring Boot、JPA 和 React 做事。

So let's say I have this enum:所以假设我有这个枚举:

public enum MyEnum {
  FIRST_ENUM("First"),
  SECOND_ENUM("Second")
}

And there's a class that contains one of the enums:还有一个包含以下枚举之一的 class :

public class MyClass {
  private int id;
  private MyEnum myEnum;
}

When I convert an instance of this class to JSON (so I can pass it to React as JSON), this is what I get:当我将此 class 的实例转换为 JSON 时(因此我可以将它作为 JSON 传递给 React),这就是我得到的:

{
  "id": 1,
  "myEnum": "FIRST_ENUM"
}

But instead I want it to use the value instead (I know I can manually create JSONObject instances, but is there a way to automatically use the value instead?):但是我希望它改为使用该值(我知道我可以手动创建 JSONObject 实例,但是有没有办法自动使用该值来代替?):

{
  "id": 1,
  "myEnum": "First"
}
public enum MyEnum {
    FIRST_ENUM("First"),
    SECOND_ENUM("Second");

    @JsonValue
    private final String name;

    MyEnum(String name) {
        this.name = name;
    }

    @JsonCreator
    public static MyEnum fromString(String string) {
        ...//find enum constant by name
    }
}

Another option is to use @JsonProperty for the enum values if the purpose of the custom name is to represent the enum's value in JSON:如果自定义name的目的是表示 JSON 中的枚举值,则另一个选项是使用@JsonProperty作为枚举值:

public enum MyEnum {
    @JsonProperty("First")  FIRST_ENUM,
    @JsonProperty("Second") SECOND_ENUM;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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