如何获取枚举类中@JsonProperty注解指定的值?
我太懂这种需求了——想用枚举避免硬编码字符串,但Jackson的@JsonProperty注解设置的值没法直接通过枚举的常规方法拿到对吧?给你几个我日常开发里常用的解决办法,都能完美解决这个问题:
方法1:借助Jackson的ObjectMapper序列化(最省心)
既然你的枚举已经用了Jackson的注解,那直接用ObjectMapper来序列化枚举实例,就能自动拿到@JsonProperty里的对应值。写个简单的工具类就行:
import com.fasterxml.jackson.databind.ObjectMapper; public class EnumJsonPropertyHelper { // 复用同一个ObjectMapper实例,避免频繁创建 private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); public static <E extends Enum<E>> String getJsonPropertyValue(E enumInstance) { try { // 序列化后会带双引号,所以要去掉 return OBJECT_MAPPER.writeValueAsString(enumInstance).trim().replace("\"", ""); } catch (Exception e) { throw new RuntimeException("Failed to fetch JSON property value for enum: " + enumInstance, e); } } }
使用的时候超简单:
// 拿到的就是"unknown" String unknownStatus = EnumJsonPropertyHelper.getJsonPropertyValue(StatusType.UNKNOWN);
方法2:在枚举类里加个自定义方法(最直观)
直接给你的StatusType枚举加一个方法,专门返回@JsonProperty的值,用的时候直接调用,一目了然:
import com.fasterxml.jackson.annotation.JsonProperty; public enum StatusType { @JsonProperty("unknown") UNKNOWN, @JsonProperty("warning") WARNING, @JsonProperty("success") SUCCESS, @JsonProperty("error") ERROR; public String getJsonPropertyValue() { try { // 通过反射拿到当前枚举常量的字段,再获取注解值 return this.getClass() .getField(this.name()) .getAnnotation(JsonProperty.class) .value(); } catch (NoSuchFieldException e) { // 理论上不会走到这,除非枚举定义出错 throw new RuntimeException("Field not found for enum constant: " + this.name(), e); } } }
调用示例:
// 得到"success" String successStatus = StatusType.SUCCESS.getJsonPropertyValue();
方法3:通用反射工具类(适合多枚举场景)
如果你的项目里有多个枚举都需要这个功能,写个通用的反射工具类,不用每个枚举都重复写方法:
import com.fasterxml.jackson.annotation.JsonProperty; import java.lang.reflect.Field; public class GenericEnumUtils { public static <E extends Enum<E>> String getJsonPropertyValue(E enumInstance) { try { Field enumField = enumInstance.getClass().getField(enumInstance.name()); JsonProperty jsonProperty = enumField.getAnnotation(JsonProperty.class); // 如果某个枚举常量没加@JsonProperty,默认返回枚举名 return jsonProperty != null ? jsonProperty.value() : enumInstance.name(); } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Invalid enum constant: " + enumInstance, e); } } }
这个工具类还做了容错处理,就算枚举里有常量没加注解也不会报错,很实用。
小提示
如果是在单元测试里用,我个人更推荐方法2或者方法3,不用额外依赖序列化操作,速度更快也更直接;如果项目里已经广泛使用Jackson,方法1也完全没问题,不用写额外的反射逻辑。
内容的提问来源于stack exchange,提问作者Your Friend Ken
相关产品推荐
相关产品推荐

