用Jackson反序列化枚举(@JsonValue)

时间:2019-12-15 22:36:25

标签: java spring jackson

我正在尝试将JSON值反序列化为以下枚举:

public enum MyEnum {
    A("1", "a"),
    B("2", "b");

    @JsonValue
    private final String code;

    private final String description;

    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    private MyEnum(String code, String description) {
        this.code = code;
        this.description = description;
    }
}

这是引发的异常:

2019-12-16 00:22:31.641 DEBUG 6680 --- [qtp798874225-20] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'request' on field 'myEnum': rejected value [2]; codes [typeMismatch.request.myEnum,typeMismatch.myEnum,typeMismatch.com.company.MyEnum,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [request.myEnum,myEnum]; arguments []; default message [myEnum]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.company.MyEnum' for property 'myEnum'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [com.company.MyEnum] for value '2'; nested exception is java.lang.ArrayIndexOutOfBoundsException: 2]]

我正在使用使用Jackson 2.9.9的Spring Boot 2.1.6。

由于我在网上看到的所有示例都非常相似且可以正常工作,因此不确定这里出了什么问题。

0 个答案:

没有答案