Json 响应对象
大约 1 分钟
Json 响应对象
封装响应对象,携带额外信息
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements Serializable {
static final long serialVersionUID = 422344123L;
/**
* 操作是否成功
*/
private boolean success = false;
/**
* 响应码
*/
private int code = -1;
/**
* 消息
*/
private String message;
/**
* 数据体
*/
private T data;
public static <T> R<T> success(T data){
return new R<>(true, 200, "操作成功", data);
}
public static <T> R<T> success(String message, T data){
return new R<>(true, 200, message, data);
}
@Deprecated
public static R<Object> failure(int code, String message){
return new R<>(false, code, message, null);
}
public static R<Object> failure(Code code){
return new R<>(false, code.code, code.message, null);
}
public static R<Object> failure(Code code, String message){
return new R<>(false, code.code, String.format("%s: %s", code.message, message), null);
}
public static <T> R<T> failure(Code code, String message, T data){
return new R<>(false, code.code, String.format("%s: %s", code.message, message), data);
}
public enum Code{
//操作成功请使用success
//OK(200, "成功"),
HEADER_REQUIRED(10000, "请提供请求头"),
DATA_NOT_EXISTS(10001, "数据不存在"),
DATA_ALREADY_EXISTS(10002, "数据重复"),
DATA_HAS_BEEN_REFERENCE(10003, "引用约束"),
INVALID_PARAMS(20001, "无效参数"),
ILLEGAL_PARAMS(20002, "非法参数"),
ILLEGAL_STATE(20003, "非法状态"),
TOKEN_REQUIRED(40001, "未提供Token"),
HAS_NO_PERMISSION(40003, "无权访问"),
FLOW_LIMITED(40010, "接口限流"),
INVALID_TOKEN(44001, "Token无效或已过期"),
SYSTEM_ERROR(50000, "系统错误"),
UNKNOWN_ERROR(-1, "异常");
final int code;
final String message;
Code(int code, String message){
this.code = code;
this.message = message;
}
}
}