How to deserialize Enum using a multi-argument constructor in Jackson2?

Given a JSON that looks like {statusCode:401} , how can I deserialize it in the following listing using Jackson 2. The main problem is that when deserializing I only have a status code, not a 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 solve this situation?

+4
source share
1 answer

Adding the following static factory method, annotated with the appropriate Jackson annotations, does 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); } } 
+2
source

Source: https://habr.com/ru/post/1435335/


All Articles