JsonResult

说明

controller 返回给前端的封装类,有以下成员变量:

  • codeint 类型,状态码,0表示成功,非0表示错误,每类错误都有错误码
  • msgString 类型,文字描述,如:添加成功!
  • data:泛型,数据,如:从数据库查询的数据,放到 data中,传给前端

依赖

  • jackson

代码

package com.stdspringboot.vo;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonResult<T> {
    //静态常量,全大写,多个字母之间用 _ 分割
    public static final int CODE_SUCCESS = 0;

    //登录失败
    public static final int CODE_LOGIN_FAIL = 100;

    //服务器报错
    public static final int CODE_SERVER_ERROR=500;

    /**
     * 校验失败,如:非空校验失败
     */
    public static final int CODE_VALIDATE_FAIL=101;
    /**
     * 表示密码 和 确认密码不相同
     */
    public static final int CODE_PASSWORD_NOT_EQUAL=102;

    /**
     * 用户名已经存在
     */
    public static final int CODE_USERNAME_EXIST=103;

    public static final int CODE_RECORD_NO_EXIST=104;

    /**
     * 表示开始日期大于结束日期
     */
    public static final int CODE_START_END_DATE=105;

    /**
     * 未登录
     */
    public static final int CODE_NO_LOGIN=106;

    private int code;
    private String msg;
    private T data;
    public JsonResult(int code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public static JsonResult validateFail(String msg){

        JsonResult jr=new JsonResult(CODE_VALIDATE_FAIL, msg);
        return jr;
    }

    /**
     * 服务器出现错误
     * @return
     */
    public static JsonResult serverError(){
        JsonResult jr=new JsonResult(CODE_SERVER_ERROR,"服务器出错,请联系管理员!");
        return jr;
    }
    /**
     * 服务器出现错误
     * @return
     */
    public static JsonResult serverError(String msg){
        JsonResult jr=new JsonResult(CODE_SERVER_ERROR,msg);
        return jr;
    }

    /**
     * 表示执行成功
     * @param msg
     * @param data 数据
     * @return
     */
    public static JsonResult success(String msg,Object data){
        JsonResult jr=new JsonResult(CODE_SUCCESS,msg);
        jr.setData(data);
        return jr;
    }

    public static JsonResult success(String msg){
        JsonResult jr=new JsonResult(CODE_SUCCESS,msg);
        return jr;
    }

    public static JsonResult fail(int code,String msg){
        JsonResult jr=new JsonResult(code,msg);
        return jr;
    }
    public String toJSON() throws JsonProcessingException {
        ObjectMapper om=new ObjectMapper();
        String jsonStr=om.writeValueAsString(this);
        return jsonStr;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}

原文出处:https://malaoshi.top/show_1IX2rn0kwlcB.html