MybatisPlus定义统一返回结果对象(json)

统一返回数据格式

项目中我们会将响应封装成json返回,一般我们会将所有接口的数据格式统一, 使前端(iOS Android, Web)对数据的操作更一致、轻松。
一般情况下,统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态以及要返回的具体数据就可以。但是一般会包含状态码、返回消息、数据这几部分内容

例如,我们的系统要求返回的基本数据格式如下:

列表:
{
    
    
  "success": true,
  "code": 20000,
  "message": "成功",
  "data": {
    
    
    "items": [
      {
    
    
        "id": "1",
    "name": "刘德华",
        "intro": "毕业于师范大学数学系,热爱教育事业,执教数学思维6年有余"
      }
    ]
  }
}
分页:
{
    
    
  "success": true,
  "code": 20000,
  "message": "成功",
  "data": {
    
    
    "total": 17,
    "rows": [
      {
    
    
        "id": "1",
        "name": "刘德华",
        "intro": "毕业于师范大学数学系,热爱教育事业,执教数学思维6年有余"
      }
    ]
  }
}
没有返回数据:
{
    
    
  "success": true,
  "code": 20000,
  "message": "成功",
  "data": {
    
    }
}

因此,我们定义统一结果

{
    
    
  "success": 布尔, //响应是否成功
  "code": 数字, //响应码
  "message": 字符串, //返回消息
  "data": HashMap //返回数据,放在键值对中
}

创建统一结果返回类

  1. 创建接口定义返回码
public interface ResultCode {
    
    
    public static Integer SUCCESS = 20000;
    public static Integer ERROR = 20001;
}
  1. 创建结果类
@Data
public class R {
    
    
    @ApiModelProperty(value = "是否成功")
    private Boolean success;
    @ApiModelProperty(value = "返回码")
    private Integer code;
    @ApiModelProperty(value = "返回消息")
    private String message;
    @ApiModelProperty(value = "返回数据")
    private Map<String, Object> data = new HashMap<String, Object>();
    private R(){
    
    }
    public static R ok(){
    
    
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }
    public static R error(){
    
    
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }
    public R success(Boolean success){
    
    
        this.setSuccess(success);
        return this;
    }
    public R message(String message){
    
    
        this.setMessage(message);
        return this;
    }
    public R code(Integer code){
    
    
        this.setCode(code);
        return this;
    }
    public R data(String key, Object value){
    
    
        this.data.put(key, value);
        return this;
    }
    public R data(Map<String, Object> map){
    
    
        this.setData(map);
        return this;
    }
}
  1. 修改Controller中的返回结果
@ApiOperation(value = "所有讲师列表")
@GetMapping
public R list(){
    
    
    List<Teacher> list = teacherService.list(null);
    return R.ok().data("items", list);
}

猜你喜欢

转载自blog.csdn.net/weixin_44313584/article/details/109855915