从@JsonProperty值获取枚举常量 [英] Get enum constant from @JsonProperty value
本文介绍了从@JsonProperty值获取枚举常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个标有@JsonProperty的枚举,用于使用Jackson进行JSON序列化/反序列化,并想获取给定String JsonProperty的枚举值:
I have an Enum marked with @JsonProperty for JSON serialization/deserialization with Jackson and would like to get the enum value for a given String JsonProperty:
public enum TimeBucket {
@JsonProperty("Daily") DAY_BUCKET,
@JsonProperty("Weekly") WEEK_BUCKET,
@JsonProperty("Monthly") MONTH_BUCKET;
}
所需的方法应该是通用/静态的(因此不必在每个枚举中都进行复制),并且将从JsonProperty中的一个中提取枚举值:
The desired method should be generic/static (so it would not be necessary to replicate it in each of the enums) and would extract an enum value out of one of the JsonProperties:
public static <T extends Enum<T>> T getEnumFromJsonProperty(Class<T> enumClass, String jsonPropertyValue)
推荐答案
可以通过以下方法获得所需的结果:
The desired result can be achieved through the following method:
public static <T extends Enum<T>> T getEnumValueFromJsonProperty(Class<T> enumClass, String jsonPropertyValue) {
Field[] fields = enumClass.getFields();
for (int i=0; i<fields.length; i++) {
if (fields[i].getAnnotation(JsonProperty.class).value().equals(jsonPropertyValue)) {
return Enum.valueOf(enumClass, fields[i].getName());
}
}
return null;
}
这篇关于从@JsonProperty值获取枚举常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文