前后端分离优雅的返回Json数据
统一返回数据格式
背景
在项目中我们会将响应封装成json返回,一般我们会将所有接口的数据统一格式,使前端(IOS,Android,Web)对数据的操作更加一致、轻松。
一般情况下,统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态及要返回的具体数据即可。但是一般会包含状态码、返回消息、数据这几部分内容,例如我介绍的返回的基本数据格式如下:
测试环境
springboot2.2.4
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
</parent>
需要依赖(测试用,与格式规范无关)
操作数据库
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
一、实现步骤
1、创建一个存放公共返回码的枚举类型
在你的实体包下创建一个ResultCode类
/**
* 公共的返回码
* 返回码code:
* 成功:10000
* 失败:10001
* 未登录:10002
* 未授权:10003
* 抛出异常:99999
*/
public enum ResultCode {
SUCCESS(true,10000,"操作成功!"),
//---系统错误返回码-----
FAIL(false,10001,"操作失败"),
UNAUTHENTICATED(false,10002,"您还未登录"),
UNAUTHORISE(false,10003,"权限不足"),
SERVER_ERROR(false,99999,"抱歉,系统繁忙,请稍后重试!"),
//---用户操作返回码 2xxxx----
MOBILEORPASSWORDERROR(false,20001,"用户名或密码错误");
//---企业操作返回码 3xxxx----
//---权限操作返回码----
//---其他操作返回码----
//操作是否成功
boolean success;
//操作代码
int code;
//提示信息
String message;
ResultCode(boolean success,int code, String message){
this.success = success;
this.code = code;
this.message = message;
}
public boolean success() {
return success;
}
public int code() {
return code;
}
public String message() {
return message;
}
}
2、创建一个Result类封装返回数据
@Data //提供getter、setter方法
@NoArgsConstructor //无参构造
public class Result {
private boolean success;
private Integer code;
private String message;
private Object data;
//不需要返回数据时使用
public Result(ResultCode code) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
}
public Result(ResultCode code,Object data) {
this.success = code.success;
this.code = code.code;
this.message = code.message;
this.data = data;
}
public Result(Integer code,String message,boolean success) {
this.code = code;
this.message = message;
this.success = success;
}
/*
* 调用ResultCode类封装常用的返回数据
*/
public static Result SUCCESS(){
return new Result(ResultCode.SUCCESS);
}
public static Result ERROR(){
return new Result(ResultCode.SERVER_ERROR);
}
public static Result FAIL(){
return new Result(ResultCode.FAIL);
}
}
2、分页展示工具类
有时候返回的数据量很大,前端页面需要有分页展示的需求,也可以提供一个对应的类提供返回数据
/**
* 分页
* {
* “success”:“成功”,
* “code”:10000
* “message”:“ok”,
* ”data“:{
* total://总条数
* rows ://数据列表
* }
* }
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageResult<T> {
private Long total;
private List<T> rows;
}
二、案例展示
为了减轻篇幅,这里只展示controller层,文章底部会详细介绍其过程
1、带有返回数据
@RestController
public class CompanyController {
@Autowired
private CompanyService companyService;
@GetMapping("/get/{id}")
public Result getCompany(@PathVariable("id") Long id) {
Company company = companyService.getById(id);
return new Result(ResultCode.SUCCESS,company);
}
}
2、无返回数据
@RestController
public class CompanyController {
@Autowired
private CompanyService companyService;
@PostMapping("/add")
public Result addCompany(@RequestBody Company company) {
companyService.addCompany(company);
return new Result(ResultCode.SUCCESS);
}
}
3、分页数据
@RestController
public class CompanyController {
@Autowired
private CompanyService companyService;
@GetMapping("/pageList")
public Result getCompanies(@RequestParam("page") Long page,
@RequestParam("limit") Long limit) {
//创建page对象,传递两个参数
Page<Company> pageCompany = new Page<>(page,limit);
//调用方法分页查询(基于mybatis-plus实现,这里不详述)
companyService.page(pageCompany,null);
//从pageCompany中获取分页数据
long total = pageCompany.getTotal();//总记录数
List<Company> records = pageCompany.getRecords();//当前页数据
PageResult<Company> pr = new PageResult<>(total,records);
return new Result(ResultCode.SUCCESS,pr);
}
}
返回数据展示
{
"success": true,
"code": 10000,
"message": "操作成功!",
"data": {
"total": 14,
"rows": [
{
"id": 1239786045768237058,
"name": "dfasf0",
"managerId": "1231241240",
},
{
"id": 1239786045768237058,
"name": "dfasf1",
"managerId": "1231241241",
},
{
"id": 1239786045768237058,
"name": "dfasf2",
"managerId": "1231241242",
},
{
"id": 1239786045768237058,
"name": "dfasf3",
"managerId": "1231241243",
}
]
}
}
三、详细流程
这边详细介绍一下带有数据返回的构造流程,剩下的留给读者解读
- 当我们调用controller层方法时
@GetMapping("/get/{id}")
public Result getCompany(@PathVariable("id") Long id) {
Company company = companyService.getById(id);
return new Result(ResultCode.SUCCESS,company);
}
- Result类调用ResultCode的构造方法