简体   繁体   English

从@JsonProperty 值获取枚举常量

[英]Get enum constant from @JsonProperty value

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:我有一个用 @JsonProperty 标记的枚举,用于使用 Jackson 进行 JSON 序列化/反序列化,并希望获取给定字符串 JsonProperty 的枚举值:

public enum TimeBucket {
    @JsonProperty("Daily") DAY_BUCKET, 
    @JsonProperty("Weekly") WEEK_BUCKET, 
    @JsonProperty("Monthly") MONTH_BUCKET;
}

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:所需的方法应该是通用/静态的(因此没有必要在每个枚举中复制它)并且将从 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM