“com.fasterxml.jackson.databind.exc.InvalidDefinitionException:即使构造函数存在,也无法构造实例”错误

问题描述 投票:0回答:1

我有这个 Java 枚举:

public enum UserTypeEnum implements EnumConverter {
USER(1),
USERS_GROUP(2);

private final int type;

UserTypeEnum(int type) {
    this.type= type;
}

@Override
@JsonValue
public int getType() {
    return type;
}
}

界面简单:

public interface EnumConverter {
int getType();
}

我将 @JsonValue 注释放在 getType 方法上方,因为我希望这些对象作为整数出现在 JSON 中。问题是,当杰克逊尝试反序列化它们时,我得到:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `UserTypeEnum` (no Creators, like default constructor, exist): no int/Int-argument constructor/factory method to deserialize from Number value (1) at {"type":1}

即使构造函数存在。我希望 Jackson 在反序列化中使用构造函数或 getType 方法。我怎样才能做到这一点?

java jackson deserialization json-value
1个回答
0
投票

您需要添加一个方法,该方法将指导 Jackson 如何将其从

JSON
反序列化为
POJO

尝试这样的事情:

@JsonCreator 
    public static UserTypeEnum forValue(int value) {
        for (UserTypeEnum userType : values()) {
            if (userType.getType() == value) {
                return userType;
            }
        }
        throw new IllegalArgumentException("Invalid type value: " + value);
    }
© www.soinside.com 2019 - 2024. All rights reserved.