首页 > 解决方案 > 检索枚举中设置的@JsonProperty 值

问题描述

如何检索@JsonProperty注释中设置的值?

我希望能够测试 REST 端点的 JSON 值。我想使用现有的枚举而不是硬编码字符串。我似乎无法弄清楚如何获取@JsonProperty注释中设置的值。

import com.fasterxml.jackson.annotation.JsonProperty;

public enum StatusType {
    @JsonProperty("unknown")
    UNKNOWN,
    @JsonProperty("warning")
    WARNING,
    @JsonProperty("success")
    SUCCESS,
    @JsonProperty("error")
    ERROR,
    @JsonProperty("info")
    INFO
}

理想情况下,我想做类似的事情:

 mvc.perform(get("/status"))
            .andExpect(jsonPath("status").value(StatusType.INFO))

标签: javajsonserializationenumsjackson

解决方案


您可以使用以下内容(不要忘记处理异常):

String value = StatusType.class.getField(StatusType.INFO.name()) 
                         .getAnnotation(JsonProperty.class).value();

或者,根据您的需要,您可以使用以下方式定义您的枚举@JsonValue

public enum StatusType {

    UNKNOWN("unknown"),
    WARNING("warning"),
    SUCCESS("success"),
    ERROR("error"),
    INFO("info");

    private String value;

    StatusType(String value) {
        this.value = value;
    }

    @JsonValue
    public String getValue() {
        return value;
    }
}

然后你可以使用:

String value = StatusType.INFO.getValue();

推荐阅读