ams
ams

Reputation: 62732

How to deserialize an Enum with a multi argument constructor in Jackson2?

Given a JSON that looks like {statusCode:401} how can I deserialize it into the following enum with Jackson 2. The main problem is that on deserialization I only have the status code not the description.

public enum RestApiHttpStatus
{
    OK(200, "Ok"),
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found");

    private final int statusCode;
    private final String description;

    private RestApiHttpStatus(int statusCode, String description)
    {
        this.statusCode = statusCode;
        this.description = description;
    }

    public int getStatusCode()
    {
        return statusCode;
    }

    public String getDescription()
    {
        return description;
    }
}

How to Configure Jackson2 to deal with this situation?

Upvotes: 4

Views: 1149

Answers (1)

ams
ams

Reputation: 62732

Adding the following static factory method annotated with proper Jackson annotations dose the trick.

@JsonCreator
public static RestApiHttpStatus valueOf(@JsonProperty("statusCode") int statusCode)
{
    if (RestApiHttpStatus.FORBIDDEN.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.FORBIDDEN;
    } else if (RestApiHttpStatus.NOT_FOUND.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.NOT_FOUND;
    } else if (RestApiHttpStatus.INTERNAL_SERVER_ERROR.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.INTERNAL_SERVER_ERROR;
    } else if (RestApiHttpStatus.BAD_REQUEST.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.BAD_REQUEST;
    } else if (RestApiHttpStatus.UNAUTHORIZED.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.UNAUTHORIZED;
    } else if (RestApiHttpStatus.OK.getStatusCode() == statusCode)
    {
        return RestApiHttpStatus.OK;
    } else
    {
        throw new IllegalArgumentException("Invlaid RestApiStatus Code " + statusCode);
    }
}

Upvotes: 2

Related Questions