public enum ClusterType {
TEMPERATURE("0402"),
HUMIDITY("0405"),
ENERGY_DETAILS("0702"),
SMART_SOCKET_STATUS("0006"),
ALARMED("0500");
private String value = null;
ClusterType(String byteStr) {
this.value = byteStr;
}
@JsonCreator
public static ClusterType fromValue(final String val){
return (ClusterType) CollectionUtils.find(Arrays.asList(ClusterType.values()), new Predicate() {
public boolean evaluate(Object object) {
ClusterType candidate = (ClusterType) object;
return StringUtils.equals(candidate.value, val);
}
});
}
@JsonValue
public String getValue(){
return value;
}
public byte[] get() {
return ByteUtils.hexStringToByteArray(value);
}
public boolean equals(String cluster) {
return StringUtils.equals(cluster, value);
}
}
我有上面的枚举
@JsonValue public String getValue(){ return value; }
部分和示例测试类,如...
public class Foo {
public static void main(String[] args) { try { ObjectMapper objectMapper = new ObjectMapper(); ClusterType []arrayRep = new ClusterType[]{ClusterType.ALARMED, ClusterType.TEMPERATURE}; Map<String, ClusterType> mapRepAsValue = new HashMap<>(); mapRepAsValue.put("1", ClusterType.ALARMED); mapRepAsValue.put("2", ClusterType.TEMPERATURE); Map<ClusterType, String> mapRepAsKey = new HashMap<>(); mapRepAsKey.put(ClusterType.ALARMED, "1"); mapRepAsKey.put(ClusterType.TEMPERATURE, "2"); System.out.println(objectMapper.writeValueAsString(arrayRep)); System.out.println(objectMapper.writeValueAsString(mapRepAsValue)); System.out.println(objectMapper.writeValueAsString(mapRepAsKey)); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
这个测试类打印出来
["0500","0402"]
{"2":"0402","1":"0500"}
{"TEMPERATURE":"2","ALARMED":"1"}
@JsonValue 在作为映射键的枚举字段上使用时不起作用。
有没有办法在序列化 map 时使用这个枚举作为键?
谢谢。
最佳答案
实际上,我认为这只是一个尚未添加的功能,根据:
https://github.com/FasterXML/jackson-databind/issues/47
所以虽然 @JsonValue
在反序列化方面对 Enums 工作得很好,但它还不适用于序列化。项目始终开放供贡献,如果有人有时间解决这个问题——这应该不是什么大工程。
关于java - @JsonValue 在枚举字段上,当此枚举用作映射键时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22023377/