使用jackson在json解析中停止接受枚举的序数值

sut*_*tha 2 java jackson

我正在尝试使用 jsckson 构建 json 解析器。下面是我的枚举类代码:

public enum Priority {
    @JsonProperty("LOW")
    LOW(100),
    @JsonProperty("MEDIUM")
    MEDIUM(200),
    @JsonProperty("HIGH")
    HIGH(300);

    private int priority;

    Priority(int i) {
        this.priority = i;
    }

    public int getPriority() {
        return priority;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我希望我的解析器只接受 3 个输入,它们是“HIGH”、“LOW”和“MEDIUM”。但它也采用序数值。例如:如果我的输入是这样的:

{
    "priority": 0
}
Run Code Online (Sandbox Code Playgroud)

它采用低优先级而不是给出错误。

我怎么能阻止这个?

sec*_*ira 6

添加以下 Bean 配置:

@Bean
public Jackson2ObjectMapperBuilderCustomizer enableFailOnNumbersForEnums() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.featuresToEnable(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS);
    }
Run Code Online (Sandbox Code Playgroud)

这将阻止 Jackson 将序数反序列化为 Enum 值。您可以在此处阅读有关启用/禁用的可用功能的更多信息:https : //github.com/FasterXML/jackson-databind/wiki/Deserialization-Features