(三)SpringBoot定义统一返回result对象

一:定义响应码枚举

package com.example.demo.core.ret;

/**
 * @Description: 响应码枚举,参考HTTP状态码的语义
 * @author 
 * @date 2018/4/19 09:42
 */
public enum RetCode {

   // 成功
   SUCCESS(200),

   // 失败
   FAIL(400),

   // 未认证(签名错误)
   UNAUTHORIZED(401),

   // 接口不存在
   NOT_FOUND(404),

   // 服务器内部错误
   INTERNAL_SERVER_ERROR(500);

   public int code;

   RetCode(int code) {
      this.code = code;
   }
}

  

二:创建返回对象实体(泛型)

package com.example.demo.core.ret;

import java.io.Serializable;

import com.alibaba.fastjson.JSON;

/**
 * @Description: 返回对象实体
 * @author 
 * @date 2018/4/19 09:43
 */
public class RetResult {

   public int code;

   private String msg;

   private T data;

   public RetResult setCode(RetCode retCode) {
      this.code = retCode.code;
      return this;
   }

   public int getCode() {
      return code;
   }

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

   public String getMsg() {
      return msg;
   }

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

   public T getData() {
      return data;
   }

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

}

  说明:code为状态码、msg为提示信息、data为返回的数据

 

四:返回结果数据格式封装

package com.example.demo.core.ret;

/**
 * @Description: 将结果转换为封装后的对象
 * @author 
 * @date 2018/4/19 09:45
 */
public class RetResponse {

   private final static String SUCCESS = "success";

   public static  RetResult makeOKRsp() {
      return new RetResult().setCode(RetCode.SUCCESS).setMsg(SUCCESS);
   }

   public static  RetResult makeOKRsp(T data) {
      return new RetResult().setCode(RetCode.SUCCESS).setMsg(SUCCESS).setData(data);
   }

   public static  RetResult makeErrRsp(String message) {
      return new RetResult().setCode(RetCode.FAIL).setMsg(SUCCESS);
   }

   public static  RetResult makeRsp(int code, String msg) {
      return new RetResult().setCode(code).setMsg(msg);
   }
   
   public static  RetResult makeRsp(int code, String msg, T data) {
      return new RetResult().setCode(code).setMsg(msg).setData(data);
   }
}

  

五:功能测试

@RequestMapping("/selectById")
public RetResult selectById(Integer id){
    UserInfo userInfo = userInfoService.selectById(id);
    return RetResponse.makeOKRsp(userInfo);
}

  改造后请求返回数据格式

{
    "code": 200,
    "msg": "success",
    "data": {
        "id": 1,
        "userName": "1"
    }
}

  

转载于:https://www.cnblogs.com/yui66/p/9615709.html

你可能感兴趣的:(java,json)