Jackson:将枚举值序列化并反序列化为整数
2022-09-01 00:45:44
请考虑以下枚举和类:
public enum State {
OFF,
ON,
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;
}
}
并考虑以下主要功能:
public static void main(String args[]) {
Machine m = new Machine("Machine 1", 8, State.OFF);
ObjectMapper mapper = new ObjectMapper();
String machineAsJsonString = mapper.writeValueAsString(m);
System.out.println(machineAsJsonString);
}
目前,该主线的输出为:
{"name" : "Machine 1", "numCores" : 8, "state" : "OFF"}
这个输出对我来说不好,因为我希望它不是 的字符串,这是枚举中的序数值。"OFF"
state
0
OFF
State
所以我想得到的实际结果是:
{"name" : "Machine 1", "numCores" : 8, "state" : 0}
有没有一些优雅的方法来让它以这种方式表现?