自定義響應資料結構

Leon_Jinhai_Sun發表於2020-10-06
package com.leon.utils;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 * @Title: JSONResult.java
 * @Package com.leon.utils
 * @Description: 自定義響應資料結構
 * 				本類可提供給 H5/ios/安卓/公眾號/小程式 使用
 * 				前端接受此類資料(json object)後,可自行根據業務去實現相關功能
 * 
 * 				200:表示成功
 * 				500:表示錯誤,錯誤資訊在msg欄位中
 * 				501:bean驗證錯誤,不管多少個錯誤都以map形式返回
 * 				502:攔截器攔截到使用者token出錯
 * 				555:異常丟擲資訊
 * 				556: 使用者qq校驗異常
 * @Copyright: Copyright (c) 2020
 * @Company: www.leon.com 
 * @version V1.0
 */
public class JSONResult {

    // 定義jackson物件
    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 響應業務狀態
    private Integer status;

    // 響應訊息
    private String msg;

    // 響應中的資料
    private Object data;
    
    @JsonIgnore
    private String ok;	// 不使用

    public static JSONResult build(Integer status, String msg, Object data) {
        return new JSONResult(status, msg, data);
    }

    public static JSONResult build(Integer status, String msg, Object data, String ok) {
        return new JSONResult(status, msg, data, ok);
    }
    
    public static JSONResult ok(Object data) {
        return new JSONResult(data);
    }

    public static JSONResult ok() {
        return new JSONResult(null);
    }
    
    public static JSONResult errorMsg(String msg) {
        return new JSONResult(500, msg, null);
    }
    
    public static JSONResult errorMap(Object data) {
        return new JSONResult(501, "error", data);
    }
    
    public static JSONResult errorTokenMsg(String msg) {
        return new JSONResult(502, msg, null);
    }
    
    public static JSONResult errorException(String msg) {
        return new JSONResult(555, msg, null);
    }
    
    public static JSONResult errorUserQQ(String msg) {
        return new JSONResult(556, msg, null);
    }

    public JSONResult() {

    }

    public JSONResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }
    
    public JSONResult(Integer status, String msg, Object data, String ok) {
        this.status = status;
        this.msg = msg;
        this.data = data;
        this.ok = ok;
    }

    public JSONResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOK() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

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

    public Object getData() {
        return data;
    }

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

	public String getOk() {
		return ok;
	}

	public void setOk(String ok) {
		this.ok = ok;
	}

}

 

相關文章