我已经实现了一个枚举类。这是代码:
public enum OfferType {
NO_OFFER("Pas d'offre", "N/A"),
LOCAL("Offre locale", "LOCAL"),
NATIONAL("Offre nationale", "NATIONAL"),
DEFAULT("DEFAULT", "DEFAULT");
// private static Logger logger = LoggerFactory.getLogger(OfferType.class);
public final String frontLabel;
public final String daoField;
OfferType(String frontLabel, String daoField) {
this.frontLabel = frontLabel;
this.daoField = daoField;
}
public static OfferType getEnum(String daoField) {
if (NO_OFFER.daoField.equals(daoField)){
return NO_OFFER;
}
if (LOCAL.daoField.equals(daoField)){
return LOCAL;
}
if (NATIONAL.daoField.equals(daoField)){
return NATIONAL;
}
//logger.error("Unknown enum value: " + daoField);
throw new IllegalArgumentException("No Enum specified for this string:"+daoField);
}
}
我有一个使用类型为“OfferType”的属性定义的类。 我应该实例化一个对象“order”并将此属性设置为该对象,如下所示:
order.setOfferType(OfferType.getEnum((rs.getString("offerType"))));
问题是,使用此设置,我将使用enum的大写字母值。我想要检索枚举的第一个值。我该怎么办?
提前致谢
答案 0 :(得分:0)
Spring使用默认的jackson序列化程序。因此,为了进行自定义序列化,您应该注释您的字段:
@JsonSerialize(using = OfferTypeSerializer.class)
private OfferType offerType;
并创建OfferTypeSerializer.class
:
public class OfferTypeSerializer extends JsonSerializer<OfferType> {
@Override
public void serialize(OrderType value, JsonGenerator jgen,
SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(value.frontLabel);
}
}
另一种方法是调用值offerType.frontLabel
并将其设置为String
或实施toString()
方法,这不是最佳解决方案:
@Override
public String toString() {
return this.frontLabel;
}
如果您要调用getEnum(String daoField)
来获取数据,则应以下一种形式编写:
public static String getEnumFrontLabel(String daoField) {
if (NO_OFFER.daoField.equals(daoField)){
return NO_OFFER.frontLabel;
}
if (LOCAL.daoField.equals(daoField)){
return LOCAL.frontLabel;
}
if (NATIONAL.daoField.equals(daoField)){
return NATIONAL.frontLabel;
}
实际上最好使用下一种返回枚举形式:
public static String getEnumFrontLabel(String daoField) {
OfferType t = getType(field);
if (t != null) {
return t.frontLabel;
}
return null;
}
public static OfferType getType(String field) {
for (OfferType type : values()) {
if (type.equals(field)) {
return type;
}
}
return null;
}