通用jsonResult封装返回结果(构造器私有化,静态构造) 待改造为其他

还有一种写法是,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));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值