gpt4 book ai didi

java - 如何在 Jackson2 中使用多参数构造函数反序列化枚举?

转载 作者:搜寻专家 更新时间:2023-11-01 03:26:34 27 4
gpt4 key购买 nike

给定一个看起来像 {statusCode:401} 的 JSON,我如何使用 Jackson 2 将它反序列化为以下枚举。主要问题是在反序列化时我只有状态代码而不是描述.

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

如何配置Jackson2来处理这种情况?

最佳答案

添加以下用正确的 Jackson 注释注释的静态工厂方法可以解决问题。

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

关于java - 如何在 Jackson2 中使用多参数构造函数反序列化枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12517445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com