0

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?

2
  • Does stackoverflow.com/questions/31689107/… answer your question? Commented Feb 15, 2024 at 11:45
  • Nope. Tried to add a static method with @JsonCreator annotation but still got the same error.. Commented Feb 15, 2024 at 13:27

1 Answer 1

0

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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

I added the method: "public static UserTypeEnum getEnum(int type)" with the @JsonCreator annotation but still got the same error... any idea why?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.