简体   繁体   English

Jackson - 使用整数字段序列化/反序列化枚举

[英]Jackson - Serialize / Deserialize Enums with Integer fields

There is a very similar question here - Jackson: Serialize and deserialize enum values as integers which deals with using Jackson to serialize and deserialize enums whose solution is pretty simple by using @JsonValue annotation.这里有一个非常相似的问题 - Jackson: Serialize and deserialize enum values as integers处理使用 Jackson 序列化和反序列化枚举,其解决方案通过使用@JsonValue注释非常简单。

This does not work in case we have an enum with an integer field like below.如果我们有一个带有如下整数字段的枚举,这将不起作用。

enum State{
    GOOD(1), BAD(-1), UGLY(0);

    int id;

    State(int id) {
        this.id = id;
    }
}

And if our requirement is to serialize and provide the actual value instead of name() .如果我们的要求是序列化并提供实际值而不是name() Say, something like {"name":"foo","state":1} representing GOOD for foo.比如说,像{"name":"foo","state":1}代表 foo 的 GOOD。 Adding @JsonValue annotation can help only in case of serialization and fails for deserialization.添加@JsonValue注释仅在序列化和反序列化失败的情况下才有帮助。 If we do not have fields, meaning that GOOD=0, BAD=1, UGLY=2, @JsonValue would be sufficient and Jackson fails to deserialize when fields exist - wrong mapping for 0 and 1 and exception for -1.如果我们没有字段,这意味着 GOOD=0、BAD=1、UGLY=2、 @JsonValue就足够了,并且当字段存在时 Jackson 无法反序列化 - 0 和 1 的映射错误,-1 的异常。

This can be achieved using Jackson annotation @JsonCreator .这可以使用 Jackson 注释@JsonCreator来实现。 For serialization, a method with @JsonValue can return an int and for deserialization, a static method with @JsonCreator can accept an int in parameter as provided below.序列化,具有方法@JsonValue可以返回int和反序列化,一个static与方法@JsonCreator如下面提供可以接受参数的int。

Code below for reference:以下代码供参考:

enum State{
    GOOD(1), BAD(-1), UGLY(0);

    int id;

    State(int id) {
        this.id = id;
    }

    @JsonValue
    int getId() {
        return id;
    }

    @JsonCreator
    static State fromId(int id){
        return Stream.of(State.values()).filter(state -> state.id == id).findFirst().get();
    }

}

Note: This is currently an open bug on Jackson library - https://github.com/FasterXML/jackson-databind/issues/1850注意:这是 Jackson 库上的一个开放错误 - https://github.com/FasterXML/jackson-databind/issues/1850

I had problems with the other solutions.我在使用其他解决方案时遇到了问题。 This worked for me (Jackson 2.9.9):这对我有用(杰克逊 2.9.9):

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
enum State{
    GOOD(1), BAD(-1), UGLY(0);

    int id;

    State(int id) {
        this.id = id;
    }

    @JsonValue
    int getId() { return id; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM