还有一种写法是,JsonResult.ok(); JsonResult.fail(); 这种写法。区别就是这种写法success值,再构造的时候就确定了。 ok是true,fail是false。
代码如下:
/**
* 通用JsonResult 构造器私有化,静态方法ok表示成功, fail表示失败。
*/
@Data
public class JsonResult<T> {
private static final long serialVersionUID =-123847128341023033L;
@JSONField
private boolean success = true;
@JSONField
private String message = null;
@JSONField
private String errorCode = "0";
@JSONField
private String errorMsg = "操作成功";
@JSONField
private Integer total = 0;
@JSONField
private List<T> data = new ArrayList();
private JsonResult() {
}
/**
* 虽然很多人都写为isSuccess(),但强烈不建议,因为相当于getSuccess()
* 可以用idea的自动生成下,如果有isSuccess(),就不会生成getSuccess()
*/
public boolean successFlag() {
return success;
}
public JsonResult(T data) {
if (data != null) {
this.data.add(data);
}
}
public JsonResult(List<T> data) {
if (data != null && data.size() > 0) {
this.data = data;
}
}
public static JsonResult ok(){
return new JsonResult();
}
public static<T> JsonResult ok(List<T> data){
JsonResult jsonResult = new JsonResult();
if (data != null && data.size() > 0) {
jsonResult.data = data;
}
return jsonResult;
}
public static<T> JsonResult ok(T data){
JsonResult jsonResult = new JsonResult();
if (data != null) {
jsonResult.data.add(data);
}
return jsonResult;
}
public static<T> JsonResult ok(String string){
JsonResult jsonResult = new JsonResult();
jsonResult.setErrorMsg(string);
return jsonResult;
}
public static JsonResult fail(String errorCode,String errorMsg){
JsonResult jsonResult = new JsonResult();
jsonResult.setSuccess(false);
jsonResult.setErrorCode(errorCode);
jsonResult.setErrorMsg(errorMsg);
return jsonResult;
}
/**
* 当有异常时,直接throw一个实现ErrorCode的异常类
* 通过global异常处理器,就可以把jsonResult封装起来,这样代码简洁优美
* 如果没有BaseException可以注释掉这个方法
*/
// public static JsonResult fail(BaseException exception){
// JsonResult jsonResult = new JsonResult();
// if (exception != null) {
// jsonResult.success = false;
// jsonResult.errorCode = exception.getErrorCode();
// jsonResult.errorMsg = exception.getErrorMsg();
// }
// return jsonResult;
// }
public static void main(String[] args) {
JsonResult jsonResult = JsonResult.ok(new Demo());
System.out.println(JSON.toJSONString(jsonResult));
}
}