gpt4 book ai didi

java - Jackson:将枚举值序列化和反序列化为整数

转载 作者:IT老高 更新时间:2023-10-28 20:43:35 25 4
gpt4 key购买 nike

考虑以下枚举和类:

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的输出是:

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

这个输出对我不好,因为我希望它是 0 而不是 state 的字符串 "OFF" ,即枚举StateOFF的序数值。

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

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

有没有什么优雅的方法让它表现得这样?

最佳答案

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

public enum State {
OFF,
ON,
UNKNOWN;

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

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

NOTE: when use for Java enums, one additional feature is that valuereturned by annotated method is also considered to be the value todeserialize from, not just JSON String to serialize as. This ispossible since set of Enum values is constant and it is possible todefine mapping, but can not be done in general for POJO types; assuch, this is not used for POJO deserialization

关于java - Jackson:将枚举值序列化和反序列化为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37833557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com