Java后端接口响应模板
@Data
@Accessors(chain = true)
@Builder
@AllArgsConstructor
@ApiModel(value = "API 返回结果")
public class ApiResult<T> implements Serializable {
private static final long serialVersionUID = 8004487252556526569L;
@ApiModelProperty(value = "响应码", example = "200")
private int status;
@ApiModelProperty(value = "是否成功", example = "ture")
private boolean success;
@ApiModelProperty(value = "响应消息", example = "Successful — 请求已完成")
private String msg;
@ApiModelProperty(value = "响应数据")
private T data;
@ApiModelProperty(value = "响应时间")
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date time;
public ApiResult() {
time = new Date();
}
public static ApiResult<Boolean> result(boolean flag) {
if (flag) {
return ok();
}
return fail();
}
public static ApiResult<Boolean> result(ApiCode apiCode) {
return result(apiCode, null);
}
public static <T> ApiResult<T> result(ApiCode apiCode, T data) {
return result(apiCode, null, data);
}
public static <T> ApiResult<T> result(ApiCode apiCode, String message, T data) {
boolean success = false;
if (apiCode.getCode() == ApiCode.SUCCESS.getCode()) {
success = true;
}
if (StringUtils.isBlank(message)) {
message = apiCode.getMessage();
}
return (ApiResult<T>) ApiResult.builder()
.status(apiCode.getCode())
.msg(message)
.data(data)
.success(success)
.time(new Date())
.build();
}
public static ApiResult<Boolean> ok() {
return ok(null);
}
public static <T> ApiResult<T> ok(T data) {
return result(ApiCode.SUCCESS, data);
}
public static <T> ApiResult<T> ok(T data, String message) {
return result(ApiCode.SUCCESS, message, data);
}
public static ApiResult ok(Integer code, String message) {
return new ApiResult()
.setSuccess(true)
.setStatus(ApiCode.SUCCESS.getCode())
.setMsg(message);
}
public static ApiResult<Map<String, Object>> okMap(String key, Object value) {
Map<String, Object> map = new HashMap<>(1);
map.put(key, value);
return ok(map);
}
public static ApiResult<Boolean> fail(ApiCode apiCode) {
return result(apiCode, null);
}
public static ApiResult<String> fail(String message) {
return result(ApiCode.OPERATION_FAIL, message, null);
}
public static <T> ApiResult<T> fail(ApiCode apiCode, T data) {
if (ApiCode.SUCCESS == apiCode) {
throw new RuntimeException("失败结果状态码不能为" + ApiCode.SUCCESS.getCode());
}
return result(apiCode, data);
}
public static ApiResult<String> fail(Integer errorCode, String message) {
return new ApiResult<String>()
.setSuccess(false)
.setStatus(errorCode)
.setMsg(message);
}
public static ApiResult<Map<String, Object>> fail(String key, Object value) {
Map<String, Object> map = new HashMap<>(1);
map.put(key, value);
return result(ApiCode.OPERATION_FAIL, map);
}
public static ApiResult<Boolean> fail() {
return fail(ApiCode.OPERATION_FAIL);
}
}