在Java中,从Integer和String反序列化枚举



我正在添加一个新的代码逻辑,使用CDC(捕获数据更改(事件。来自DB的status字段表示为int,应该反序列化为枚举。这是枚举:

public enum Status {
ACTIVE(21),
CANCELLED(22),
EXPIRED(23),
FAILED(24),
PAUSED(25);
private static final Map<Integer, Status> map = new HashMap<>();
static {
for (val value : Status.values()) {
if (map.put(value.getId(), value) != null) {
throw new IllegalArgumentException("duplicate id: " + value.getId());
}
}
}
public static Status getById(Integer id) {
return map.get(id);
}
private Integer id;
Status(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
  1. 枚举不能是"开箱即用";从Integer开始序列化不是从0开始(接收index value outside legal index range异常(
  2. 今天,我们已经有了一个接收字符串(例如"ACTIVE"(并成功反序列化它的流。我不想改变/损害这种能力

我尝试在此处添加@JsonCreator

@JsonCreator
public static SubscriptionStatus getById(Integer id) {
return map.get(id);
}

但是现在不可能再反序列化String了。我更喜欢有一个简单的解决方案,而不是为它创建一个自定义的反序列化程序(我认为应该有一个(。

试试这样的东西:

@JsonCreator
public static Status get(Object reference) {
if( reference instanceof Number num) {
return getById(num.intValue());
} else if( reference instanceof String str) {
//the string might contain the id as well, e.g. "21" for ACTIVE
//so you might want to check the string for this, if this is expected
return Enum.valueOf(Status.class, str);
}

return null;
}

这基本上接受任何类型的值,检查它是什么,并相应地解析枚举值。

相关内容

最新更新