杰克逊:将枚举值序列化和反序列化为整数 [英] Jackson: Serialize and deserialize enum values as integers
问题描述
考虑以下枚举和类:
public enum State {
ON,
OFF,
UNKNOWN
}
public class Machine {
String name;
int numCores;
州州;
public Machine(String name,int numCores,State state){
this.name = name;
this.numCores = numCores;
this.state = state;
}
}
请考虑以下主要功能:
public static void main(String args []){
Machine m = new Machine(Machine 1,8,OFF) ;
ObjectMapper mapper = new ObjectMapper();
String machineAsJsonString = mapper.writeValueAsString(m);
System.out.println(machineAsJsonString);
}
目前,这个主要的输出是:
{name:Machine 1,numCores:8,state:OFF}
这个输出对我来说不好,而不是字符串OFF
状态
,我希望它是 1
,这是 OFF
在枚举状态
中。
所以我想得到的实际结果是:
$$$$$$$$$
有没有一些优雅的方式来使其行为这样?
解决方案它应该通过指定
JsonValue
mapper。public enum State {
ON,
OFF,
UNKNOWN;
@JsonValue
public int toValue(){
return ordinal();
}
}
这也适用于反序列化,如Javadoc注意:在使用Java枚举时,还有一个附加功能:
@JsonValue
注释:
<是通过annotated方法返回的值
也被认为是
反序列化的值,而不仅仅是将JSON String序列化为。这是
可能,因为Enum值的集合是不变的,并且可以
定义映射,但POJO类型通常不能完成;作为
这样,这不用于POJO反序列化
Consider the following enum and class:
public enum State { ON, OFF, UNKNOWN } public class Machine { String name; int numCores; State state; public Machine(String name, int numCores, State state) { this.name = name; this.numCores = numCores; this.state = state; } }
And consider the following main function:
public static void main(String args[]) { Machine m = new Machine("Machine 1", 8, OFF); ObjectMapper mapper = new ObjectMapper(); String machineAsJsonString = mapper.writeValueAsString(m); System.out.println(machineAsJsonString); }
Currently, the output of this main is:
{"name" : "Machine 1", "numCores" : 8, "state" : "OFF"}
This output is not good for me, as instead of the string
"OFF"
forstate
, I would like it to be1
, which is the ordinal value ofOFF
in the enumState
.So the actual result I want to get is:
{"name" : "Machine 1", "numCores" : 8, "state" : 1}
Is there some elegant way to make it behave this way?
解决方案It should work by specifying
JsonValue
mapper.public enum State { ON, OFF, UNKNOWN; @JsonValue public int toValue() { return ordinal(); } }
This works for deserialization also, as noted in Javadoc of
@JsonValue
annotation:NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization
这篇关于杰克逊:将枚举值序列化和反序列化为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!