Jackson:将枚举值序列化和反序列化为整数 [英] Jackson: Serialize and deserialize enum values as integers

查看:51
本文介绍了Jackson:将枚举值序列化和反序列化为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下枚举和类:

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);
}

目前,这个main的输出是:

Currently, the output of this main is:

{"name" : "Machine 1", "numCores" : 8, "state" : "OFF"}

这个输出对我来说不好,因为对于 state,我希望它是 0"OFF">,是枚举StateOFF的序号值.

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.

所以我想得到的实际结果是:

{"name" : "Machine 1", "numCores" : 8, "state" : 0}

是否有一些优雅的方法可以让它表现得如此?

Is there some elegant way to make it behave this way?

推荐答案

它应该通过指定 JsonValue 映射器来工作.

It should work by specifying JsonValue mapper.

public enum State {
    OFF,
    ON,
    UNKNOWN;

    @JsonValue
    public int toValue() {
        return ordinal();
    }
}  

这也适用于反序列化,如 @JsonValue 注释的 Javadoc 中所述:

This works for deserialization also, as noted in Javadoc of @JsonValue annotation:

注意:当用于 Java 枚举时,一个附加功能是该值带注释的方法返回的值也被认为是反序列化,而不仅仅是要序列化的 JSON 字符串.这是可能,因为 Enum 值集是恒定的,并且有可能定义映射,但对于 POJO 类型一般无法完成;作为这样,这不用于 POJO 反序列化

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

这篇关于Jackson:将枚举值序列化和反序列化为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆