SpringBoot之封裝json對象返回json數據

/** * @description:封裝json對象,全部返回結果都使用它 **/
public class Result<T> { private int code;// 業務自定義狀態碼

    private String msg;// 請求狀態描述,調試用

    private T data;// 請求數據,對象或數組都可

    public Result() { } /** * 成功時候的調用 * @param data data * @param <T> t * @return Result */
    public static <T> Result<T> success(T data){ return new Result<T>(data); } /** * 失敗時候的調用 * @param codeMsg codeMsg * @param <T> t * @return Result */
    public static <T> Result<T> error(CodeMsg codeMsg){ return new Result<T>(codeMsg); } /** * 成功的構造函數 * @param data data */
    public Result(T data){ this.code = 200;//默認200是成功
        this.msg = "SUCCESS"; this.data = data; } public Result(int code, String msg) { this.code = code; this.msg = msg; } /** * 失敗的構造函數 * @param codeMsg codeMsg */
    private Result(CodeMsg codeMsg) { if(codeMsg != null) { this.code = codeMsg.getCode(); this.msg = codeMsg.getMsg(); } } 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; } public T getData() { return data; } public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}'; } }
public class CodeMsg { private int code; private String msg; 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; } /*服務端異常*/
    public static CodeMsg SUCCESS = new CodeMsg(200,"SUCCESS"); public static CodeMsg SERVER_ERROR = new CodeMsg(100,"系統異常:%s"); public static CodeMsg BIND_ERROR = new CodeMsg(101,"(綁定異常)參數校驗異常:%s"); /*用佔位符 傳入一個參數*/
    public static CodeMsg SESSION_ERROR = new CodeMsg(102,"沒有SESSION!"); /*用佔位符 傳入一個參數*/
    public static CodeMsg REQUEST_ERROR = new CodeMsg(103,"非法請求!"); /*用佔位符 傳入一個參數*/
    public static CodeMsg REQUEST_OVER_LIMIT = new CodeMsg(104,"請求次數過多!"); /*用佔位符 傳入一個參數*/

    private CodeMsg( ) { } private CodeMsg( int code,String msg ) { this.code = code; this.msg = msg; } //不定參的構造函數
    public CodeMsg fillArgs(Object... args) { int code = this.code; String message = String.format(this.msg, args); return new CodeMsg(code, message); } @Override public String toString() { return "CodeMsg [code=" + code + ", msg=" + msg + "]"; } }
相關文章
相關標籤/搜索