gpt4 book ai didi

java - 根据枚举验证 JSON 字段

转载 作者:行者123 更新时间:2023-11-30 06:22:15 25 4
gpt4 key购买 nike

我正在使用 Jackson 的 ObjectMapper 直接从接收到的 JSON 构建我的 POJO。为此,我使用 @JsonProperty 注释来注释我的字段(在本例中,字段是抽象方法,因为我使用 AutoValue 来减少样板文件)。

现在,我的 POJO 中的一些字段是枚举,其中 JSON 显然包含常规字符串。我想以某种方式验证这些 JSON 字段确实在构造对象之前提交给给定的枚举类型。

这是示例。

@JsonProperty(value = "messageType")
public abstract Optional<MessageType> messageType();

该属性的类型为enum MessageType,对应的JSON字段为ie。 "messageType": "A_1"这是一个字符串。

现在,如果“messageType”类似于“blabla”,我希望验证失败。

有没有办法使用 Hibernate Validator 通过注释来验证这一点?

最佳答案

@JsonProperty(value = "messageType") public abstract Optional messageType();

假设您有 MessageType 作为具有不同值 A_1、A_2...的枚举

创建一个静态实用方法来序列化/反序列化接收/发送的 json 值中的枚举值

public static <T extends Enum<T>> T getEnumFromJson(Class<T> enumClass, String value) 
{
if(enumClass == null) throw new IllegalArgumentException("EnumClass value can't be null");
for(Enum<?> enumValue : enumClass.getEnumConstants()){
if(enumValue.toString().equalsIgnoreCase(value)){
return (T) enumValue;
}
}
//Validation message construct to give more meaningful details to end-user
StringBuilder erroMsg = new StringBuilder();
boolean bFirst = true;
for(Enum<?> enumValue : enumClass.getEnumConstants()) {
errorMessage.append(bFirst ? "": ", ").append(enumValue);
bFirst = false;
}

throw new IllegalArgumentException(value + " is invalid value, Supported value are "+ errorMessage);
}

//Enum as represented below
public enum MessageType {
A_1,
A_2,
A_3

@JsonCreator
public static MessageType fromValue(String value){
return getEnumFromJson(MessageType.class, value);
}

@JsonValue
public String toJson(){
return name().toLowerCase();
}

}

关于java - 根据枚举验证 JSON 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47882238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com