cn.xuqiudong.common.base.model.BaseResponse Maven / Gradle / Ivy
package cn.xuqiudong.common.base.model;
import cn.xuqiudong.common.base.enums.ResultMsg;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 返回JSON的基本格式
*
* @author VIC
*
*/
public final class BaseResponse {
private static final Logger logger = LoggerFactory.getLogger(BaseResponse.class);
/**
* 状态码 0为正确
*/
private int code;
/**
* 错误提示信息
*/
private String msg;
/**
* 数据对象
*/
private T data;
public static BaseResponse error(ResultMsg msg) {
return error(msg.getCode(), msg.getMsg());
}
public static BaseResponse judge(boolean judge) {
return judge ? success() : error();
}
/** 构建操作成功的对象 */
public static BaseResponse success(T data) {
return new BaseResponse(0, "", data);
}
/** 构建操作成功的对象 */
public static BaseResponse success() {
return new BaseResponse(0, "");
}
public static BaseResponse error() {
return error(999, "");
}
/** 构建操作失败的对象 */
public static BaseResponse error(String msg) {
return error(999, msg);
}
/** 构建操作失败的对象 */
public static BaseResponse error(int code, String msg) {
return new BaseResponse(code, msg);
}
/**
* 转JSON
*/
public String toJson() {
try {
return MAPPER.writeValueAsString(this);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return "{" + "\"code\":" + code + ",\"msg\":\"" + msg + "\",\"data\":\"" + data + "\"}";
}
@Override
public String toString() {
return this.toJson();
}
public BaseResponse() {
}
private BaseResponse(int code, String msg) {
super();
this.code = code;
this.msg = msg;
}
private BaseResponse(int code, String msg, T data) {
super();
this.code = code;
this.msg = msg;
this.data = data;
}
public BaseResponse> appendMsg(String msg) {
this.msg += msg;
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public BaseResponse> setMsg(String msg) {
this.msg = msg;
return this;
}
public T getData() {
return data;
}
public BaseResponse setData(T data) {
this.data = data;
return this;
}
public boolean isSuccess() {
return 0 == code;
}
private static final ObjectMapper MAPPER = new ObjectMapper();
}