Consider the following enum and class:
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;
}
}
And consider the following main function:
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);
}
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"
for state
, I would like it to be 0
, which is the ordinal value of OFF
in the enum State
.
So the actual result I want to get is:
{"name" : "Machine 1", "numCores" : 8, "state" : 0}
Is there some elegant way to make it behave this way?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…