user16076953
user16076953

Reputation: 31

"com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of" error even though constructor exists

I have this Java enum:

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;
}
}

With the simple interface:

public interface EnumConverter {
int getType();
}

I put the @JsonValue annotation above the getType method as I wanted these objects to appear in the JSON as integers. The problem is that when Jackson tries to deserialize them, I get:

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}

Even though the constructor exists. I want Jackson to use either the constructor or the getType method in deserialization. How can I achieve that?

Upvotes: 0

Views: 646

Answers (1)

tamtejszystan
tamtejszystan

Reputation: 165

You need to add a method, that will guide Jackson on how to deserialize it from JSON to POJO.

Try something like this:

@JsonCreator 
    public static UserTypeEnum fromValue(int value) {
        for (UserTypeEnum userType : values()) {
            if (userType.getType() == value) {
                return userType;
            }
        }
        throw new IllegalArgumentException("Invalid type value: " + value);
    }

or with Stream API:

@JsonCreator
public static UserTypeEnum fromValue(int value) {
    return Arrays.stream(UserTypeEnum.values())
                 .filter(userType -> userType.getType() == value)
                 .findFirst()
                 .orElseThrow(() -> new IllegalArgumentException("Invalid type value: " + value));
}

Upvotes: 0

Related Questions