Java后端返回Json数据规范 一,统一返回的Json数据格式 返回内容: 状态码,返回消息,数据
1.列表数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 { "success" : true , "code" : 20000 , "message" : "成功" , "data" : { "items" : [ { "id" : "1" , "name" : "小王" , "identified" : "用户" } ] } }
2.分页数据 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 { "success" : true , "code" : 20000 , "message" : "成功" , "data" : { "total" : 17 , "rows" : [ { "id" : "1" , "name" : "小王" , "identified" : "用户" } ] } }
3.无返回数据 1 2 3 4 5 6 { "success" : true , "code" : 20000 , "message" : "成功" , "data" : { } }
4.返回数据失败 1 2 3 4 5 6 { "success" : false , "code" : 20001 , "message" : "失败" , "data" : { } }
统一定义格式: 1 2 3 4 5 6 { "success" : 布尔, "code" : 数字, "message" : 字符串, "data" : HashMap }
二,创建统一返回结果类 1.创建接口定义返回码 创建工具包utils,创建接口命名为ResultCode.java
1 2 3 4 5 6 7 8 package com.atguigu.commonutils;public interface ResultCode { public static Integer SUCCESS = 20000 ; public static Integer ERROR = 20001 ; }
2.创建结果类 创建类Result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 @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
1 2 3 4 5 6 @ApiOperation(value = "所有列表") @GetMapping("findAllTeacher") public Result list () { List<Teacher> list = teacherService.list(null ); return Result.ok().data("items" , list); }
空数据 这里是根据id删除用户信息,因此无返回数据
1 2 3 4 5 6 7 8 @ApiOperation(value = "根据ID删除") @DeleteMapping("{id}") public Result removeById ( @ApiParam(name = "id", value = "ID", required = true) @PathVariable String id) { teacherService.removeById(id); return Result.ok(); }