SpringBoot 中设计统一返回json结果集

81 阅读1分钟
  1. 首先看一下目录结构

1.png

ResultCode 接口文件 内容 如下:

package com.school.commonutils;

/**
 * @User: Json
 * @Date: 2021/11/8
 **/
public interface ResultCode {

    public static Integer SUCCESS=200;

    public static Integer ERROR=400;
}

3. R 文件中内容如下 :

package com.school.commonutils;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * @User: Json
 * @Date: 2021/11/8
 * 统一返回结果
 **/
@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;
    }
}

4. 引入定义好的 模块

在使用的地方的 pom.xml 中 写引入

<!--        引入公共模块创建的 common_utils 的配置文件
     artifactId 在这个标签中写 会有提示-->
<dependency>
    <groupId>com.schoolWeb</groupId>
    <artifactId>common_utils</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

5. 进行测试

2.png