Saq*_*med 4 java enums json hibernate alpacajs
我需要使用包含空格的字符串和它们在int中的值来实现enun,如:
public enum status{
Active(1),
Inactive(2);
}
Run Code Online (Sandbox Code Playgroud)
因为我正在使用它与hibernate,并将其转换为JSON的羊驼js形式.
喜欢:
[{"text": "Inactive", "value":"2"},{"text": "Active", "value":"1"}]
Run Code Online (Sandbox Code Playgroud)
我不知道如何制作这种类型的枚举.
Cha*_*ara 20
你不能在字符串之间放置空格.而不是你可以使用下划线如下:
In_Active
Run Code Online (Sandbox Code Playgroud)
你可以这样使用:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将多个值合而为一enum,甚至可以使用getter来处理它们。这是我曾经使用的一个示例(我尝试使其适应您的问题):
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();
}
}
Run Code Online (Sandbox Code Playgroud)
因此,在您的代码中,您可以简单地使用Status.ACTIVE它,它将代表您的Enum实例,该实例保存value并保留text您想要的方式