epol
epol

Reputation: 1044

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:

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:

public static <T extends Enum<T>> T getEnumFromJsonProperty(Class<T> enumClass, String jsonPropertyValue)

Upvotes: 0

Views: 1143

Answers (1)

epol
epol

Reputation: 1044

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;
}

Upvotes: 2

Related Questions