关于json:如何在Java中使像枚举之类的键值

How to make key value like enum in java

本问题已经有最佳答案,请猛点这里访问。

我需要制作一个Enum,其中包含一些带空格的字符串及其在int中的值,例如:

1
2
3
4
public enum status{
Active(1),
Inactive(2);
}

因为我将其与休眠一起使用,并且还将其转换为羊驼js表单的JSON。

like:

1
[{"text":"Inactive","value":"2"},{"text":"Active","value":"1"}]

我被困在制作Enum中。如何制作这样的Enum类型?


您不能在字符串之间放置空格。代替,您可以使用下划线,如下所示:

1
In_Active

您可以使用以下方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum Status {

    ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);

    private final String key;
    private final Integer value;

    Status(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }
    public Integer getValue() {
        return value;
    }
}


您可以在一个enum中包含多个值,甚至可以使用getter来处理它们。这是我曾经使用过的一个示例(我尝试使其适应您的问题):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public enum Status{

    ACTIVE(1,"Active"),
    INACTIVE(2,"In Active");

    private final Integer value;
    private final String text;

    /**
     * A mapping between the integer code and its corresponding text to facilitate lookup by code.
     */

    private static Map<Integer, Status> valueToTextMapping;

    private Status(Integer value, String text){
        this.value = value;
        this.text = text;
    }

    public static Status getStatus(Integer i){
        if(valueToTextMapping == null){
            initMapping();
        }
        return valueToTextMapping.get(i);
    }

    private static void initMapping(){
        valueToTextMapping = new HashMap<>();
        for(Status s : values()){
            valueToTextMapping.put(s.value, s);
        }
    }

    public Integer getValue(){
        return value;
    }

    public String getText(){
        return text;
    }

    @Override
    public String toString(){
        final StringBuilder sb = new StringBuilder();
        sb.append("Status");
        sb.append("{value=").append(value);
        sb.append(", text='").append(text).append('\'')
        sb.append('}');
        return sb.toString();
    }
}

因此在您的代码中,您可以简单地使用Status.ACTIVE,它将表示您的Enum的实例,该实例以您想要的方式保存valuetext


您不能在标识符中间放置空格。

查看此链接是否可以为Java中的枚举分配数值?用于将值分配给Java中的枚举。