我一直在寻找枚举序列化的解决方案,我终于做出了一个解决方案。
https://github.com/sirgilligan/EnumerationSerialization
https://digerati-illuminatus.blogspot.com/2022/10/java-enum-generic-serializer-and.html
它使用了一个新的注释和两个新类EnumerationSerializer和EnumerationDeserializer。您可以子类化EnumerationDeserializer,并创建一个设置枚举class的类(典型方法),或者您可以注释枚举,并且不必拥有EnumerationDeserializer的子类。
@JsonSerialize(using = EnumerationSerializer.class)
@JsonDeserialize(using = EnumerationDeserializer.class)
@EnumJson(serializeProjection = Projection.NAME, deserializationClass = RGB.class)
enum RGB {
RED,
GREEN,
BLUE
}
注意ContextualDeserializer的实现如何从注释中提取类。
https://github.com/sirgilligan/EnumerationSerialization/blob/main/src/main/java/org/example/EnumerationDeserializer.java
这里有很多很好的代码,可以提供一些见解。
对于你的具体问题,你可以这样做:
@JsonSerialize(using = EnumerationSerializer.class)
@JsonDeserialize(using = EnumerationDeserializer.class)
@EnumJson(serializeProjection = Projection.NAME, deserializationClass = Event.class)
public enum Event {
FORGOT_PASSWORD("forgot password");
//This annotation is optional because the code looks for value or alias.
@EnumJson(serializeProjection = Projection.VALUE)
private final String value;
private Event(final String description) {
this.value = description;
}
}
或者你可以这样做:
@JsonSerialize(using = EnumerationSerializer.class)
@JsonDeserialize(using = EnumerationDeserializer.class)
@EnumJson(serializeProjection = Projection.NAME, deserializationClass = Event.class)
public enum Event {
FORGOT_PASSWORD("forgot password");
private final String value;
private Event(final String description) {
this.value = description;
}
}
这就是你要做的。
然后,如果您有一个“有”事件的类,您可以注释每个事件以您想要的方式序列化。
class EventHolder {
@EnumJson(serializeProjection = Projection.NAME)
Event someEvent;
@EnumJson(serializeProjection = Projection.ORDINAL)
Event someOtherEvent;
@EnumJson(serializeProjection = Projection.VALUE)
Event yetAnotherEvent;
}