java - 检索枚举中设置的@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))
解决方案
您可以使用以下内容(不要忘记处理异常):
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();
推荐阅读
- swift - 我的相机应用程序的 Swift 代码中有几个错误
- escaping - 防止 Excel 在 JXL API 创建的文件中使 URL 可点击
- java - 如何使用 Springboot 和 Thymeleaf 使用 LocalTime 在两个日期之间进行验证
- typescript - 从没有属性或属性列表的接口创建类型
- sql - 用户同时更新同一行 SQL Server
- python - 仅替换字符串的结尾
- php - 将 php 网页发送到文件夹并将内容显示为 html
- vb.net - 如何将 SQL 数据库中最后一行的选定单元格值放入两个标签中?
- hazelcast - Hazelcast 和对自定义序列化程序的需求;在创建服务器时有效,但在连接到现有服务器时无效
- python - 为Windows制作一个可执行的kivy文件,pyinstaller有问题