Java后端返回Json数据规范
一,统一返回的Json数据格式
返回内容:
状态码,返回消息,数据
1.列表数据
代码语言:javascript复制{
"success": true,
"code": 20000,
"message": "成功",
"data": {
"items": [
{
"id": "1",
"name": "小王",
"identified": "用户"
}
]
}
}
2.分页数据
代码语言:javascript复制{
"success": true,
"code": 20000,
"message": "成功",
"data": {
"total": 17,
"rows": [
{
"id": "1",
"name": "小王",
"identified": "用户"
}
]
}
}
3.无返回数据
代码语言:javascript复制{
"success": true,
"code": 20000,
"message": "成功",
"data": {}
}
4.返回数据失败
代码语言:javascript复制{
"success": false,
"code": 20001,
"message": "失败",
"data": {}
}
统一定义格式:
代码语言:javascript复制{
"success": 布尔, //响应是否成功
"code": 数字, //响应码
"message": 字符串, //返回消息
"data": HashMap //返回数据,放在键值对中
}
二,创建统一返回结果类
1.创建接口定义返回码
创建工具包utils,创建接口命名为ResultCode.java
代码语言:javascript复制package com.atguigu.commonutils;
public interface ResultCode {
public static Integer SUCCESS = 20000; //成功码
public static Integer ERROR = 20001; //失败码
}
2.创建结果类
创建类Result
代码语言:javascript复制@Data
public class Result {
@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 Result(){}
public static Result ok(){
Result r = new Result();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
public static Result error(){
Result r = new Result();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public Result success(Boolean success){
this.setSuccess(success);
return this;
}
public Result message(String message){
this.setMessage(message);
return this;
}
public Result code(Integer code){
this.setCode(code);
return this;
}
public Result data(String key, Object value){
this.data.put(key, value);
return this;
}
public Result data(Map<String, Object> map){
this.setData(map);
return this;
}
}
3.Controller中的返回统一数据格式的Json示例
列表数据 在返回的json的中,有一个键值为data的Hashmap 使用mybatis plus无条件(wrapper为null,查询全部)查询所有用户的信息 所有信息返回一个list 将list放入hashmap中,键值为items
代码语言:javascript复制@ApiOperation(value = "所有列表")
@GetMapping("findAllTeacher")
public Result list(){
List<Teacher> list = teacherService.list(null);
return Result.ok().data("items", list);
}
空数据 这里是根据id删除用户信息,因此无返回数据
代码语言:javascript复制@ApiOperation(value = "根据ID删除")
@DeleteMapping("{id}")
public Result removeById(
@ApiParam(name = "id", value = "ID", required = true)
@PathVariable String id){
teacherService.removeById(id);
return Result.ok();
}