Jackson: Serialize and deserialize enum values as integers
<p>Consider the following enum and class:</p>
<pre><code>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;
    }
}
</code></pre>
<p>And consider the following main function:</p>
<pre><code>public static void main(String args[]) {
    Machine m = new Machine(&quot;Machine 1&quot;, 8, State.OFF);
    ObjectMapper mapper = new ObjectMapper();
    String machineAsJsonString = mapper.writeValueAsString(m);
    System.out.println(machineAsJsonString);
}
</code></pre>
<p>Currently, the output of this main is:</p>
<pre><code>{&quot;name&quot; : &quot;Machine 1&quot;, &quot;numCores&quot; : 8, &quot;state&quot; : &quot;OFF&quot;}
</code></pre>
<p>This output is not good for me, as instead of the string <code>&quot;OFF&quot;</code> for <code>state</code>, I would like it to be <code>0</code>, which is the ordinal value of <code>OFF</code> in the enum <code>State</code>.</p>
<p><strong>So the actual result I want to get is:</strong></p>
<pre><code>{&quot;name&quot; : &quot;Machine 1&quot;, &quot;numCores&quot; : 8, &quot;state&quot; : 0}
</code></pre>
<p>Is there some elegant way to make it behave this way?</p>