java - 如何在java中使用枚举键值
问题描述
我想用键值在 java 11 中创建一个枚举类我创建一个像这样的枚举
public 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;
}
}
当我做 Saison saison.getvalues() 我得到这样的问题
[
"ACTIVE",
"INACTIVE"
]
但我想要这样
[
{
"Key": "Inactive",
"value":"2"
},
{
"Key": "Active",
"value":"1"
}
]
我怎样才能调用我的枚举 tio 得到这样的结果
解决方案
没有什么可以阻止您返回包含该key,value
对的映射条目。
enum Status {
ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);
private final String key;
private final int value;
Status(String key, int value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public int getValue() {
return value;
}
public Entry<String,Integer> getBoth() {
return new AbstractMap.SimpleEntry<>(key, value);
}
}
Entry<String,Integer> e = Status.ACTIVE.getBoth();
System.out.println("Key: = " + e.getKey());
System.out.println("Value: = " + e.getValue());
或打印条目的 toString() 值。
System.out.println(e);
印刷
Key: = Active
Value: = 1
Active=1
您还可以覆盖 Enum 的 toString 并执行类似的操作。
public String toString() {
return String.format("\"key\": \"%s\",%n\"value\": \"%s\"",
getKey(), getValue());
}
System.out.println(Status.ACTIVE);
印刷
"key": Active",
"value": "1"
推荐阅读
- python - 具有多个字符串条件的while循环不能离开循环
- node.js - 如何在 node.js 中创建 SAML 断言签名
- javascript - slick.js 中多个项目滑块的响应性问题
- r - bookdown数字格式:顺序编号和部分编号
- spring - ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) 在使用 WebClient 时显示类之间的不一致
- html - 如何使用 flex-grow 像尺寸一样缩放边距?
- flutter - 如何在颤动中释放视频播放器
- c# - 接口类型的泛型类型的隐式转换失败
- docker - Docker 容器不响应请求
- laravel - POST请求的Laravel分页