【发布时间】:2020-05-14 19:03:28
【问题描述】:
我正在尝试反序列化为枚举,但 JSON 值(小写)与枚举常量(大写)不同。
这是枚举:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum ContractTypes {
@JsonProperty("product")
PRODUCT("product"),
@JsonProperty("service")
SERVICE("service");
private String value;
}
如您所见,我使用@JsonPropertyannotation 对元素进行了注释,以尝试将提供的值映射到合适的常量。
我还尝试使用@JsonValue 注释对属性value 进行注释。在这两种情况下,我都得到了相同的结果:
Field error in object 'createContractRequestDto' on field 'contractType': rejected value [product]; codes [typeMismatch.createContractRequestDto.contractType,typeMismatch.contractType,typeMismatch.enm.ContractTypes,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [createContractRequestDto.contractType,contractType]; arguments []; default message [contractType]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'enm.ContractTypes' for property 'contractType'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [enm.ContractTypes] for value 'product'; nested exception is java.lang.IllegalArgumentException: No enum constant enm.ContractTypes.product]]
为什么@JsonProperty 和@JsonValue 注释不起作用?我必须如何编写解决方案以将 JSON 值映射到合适的枚举元素?
【问题讨论】:
标签: java json enums jackson jackson-databind