从@JsonProperty值获取枚举常量

huangapple go评论110阅读模式
英文:

Get enum constant from @JsonProperty value

问题

我有一个带有@JsonProperty注解的枚举,用于使用Jackson进行JSON序列化/反序列化,并且想要根据给定的String JsonProperty获取枚举值:

  1. public enum TimeBucket {
  2. @JsonProperty("Daily") DAY_BUCKET,
  3. @JsonProperty("Weekly") WEEK_BUCKET,
  4. @JsonProperty("Monthly") MONTH_BUCKET;
  5. }

期望的方法应该是通用的/静态的(这样就不需要在每个枚举中复制它),并且可以从JsonProperties中提取枚举值:

  1. public static <T extends Enum<T>> T getEnumFromJsonProperty(Class<T> enumClass, String jsonPropertyValue)
英文:

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:

  1. public enum TimeBucket {
  2. @JsonProperty(&quot;Daily&quot;) DAY_BUCKET,
  3. @JsonProperty(&quot;Weekly&quot;) WEEK_BUCKET,
  4. @JsonProperty(&quot;Monthly&quot;) MONTH_BUCKET;
  5. }

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:

  1. public static &lt;T extends Enum&lt;T&gt;&gt; T getEnumFromJsonProperty(Class&lt;T&gt; enumClass, String jsonPropertyValue)

答案1

得分: 2

以下是翻译好的内容:

所需的结果可以通过以下方法实现:

  1. public static <T extends Enum<T>> T getEnumValueFromJsonProperty(Class<T> enumClass, String jsonPropertyValue) {
  2. Field[] fields = enumClass.getFields();
  3. for (int i = 0; i < fields.length; i++) {
  4. if (fields[i].getAnnotation(JsonProperty.class).value().equals(jsonPropertyValue)) {
  5. return Enum.valueOf(enumClass, fields[i].getName());
  6. }
  7. }
  8. return null;
  9. }
英文:

The desired result can be achieved through the following method:

  1. public static &lt;T extends Enum&lt;T&gt;&gt; T getEnumValueFromJsonProperty(Class&lt;T&gt; enumClass, String jsonPropertyValue) {
  2. Field[] fields = enumClass.getFields();
  3. for (int i=0; i&lt;fields.length; i++) {
  4. if (fields[i].getAnnotation(JsonProperty.class).value().equals(jsonPropertyValue)) {
  5. return Enum.valueOf(enumClass, fields[i].getName());
  6. }
  7. }
  8. return null;
  9. }

huangapple
  • 本文由 发表于 2020年10月19日 00:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64415585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定