springboot处理统一返回json数据格式
Posted walblog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot处理统一返回json数据格式相关的知识,希望对你有一定的参考价值。
第一步,写一个实体类JsonResultEntity,定义返回的参数
package com.bujiang.magic.common.utils; public class JsonResultEntity { private Object data; private String message; private Integer code; public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
第二步,写一个工具类ResponseEntity
package com.bujiang.magic.common.utils; public class JsonResultUtils{ public static JsonResultEntity success(Object object) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setData(object); jsonResult.setCode(200); jsonResult.setMessage("success"); return jsonResult; } public static JsonResultEntity success(Object object, Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setData(object); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } public static JsonResultEntity success() { return success(null); } public static JsonResultEntity error(Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } public static JsonResultEntity success(Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } }
第三步,测试
DemoController:
@ApiOperation(value = "测试统一json返回", notes = "") @RequestMapping(value = "testJsonReturn", method = RequestMethod.POST) public ResponseEntity<JsonResultEntity> testJsonReturn() { return userService.testJsonReturn(); }
UserService:
/** * 测试json统一返回数据 * @return */ ResponseEntity<JsonResultEntity> testJsonReturn();
UserServiceImpl
@Override public ResponseEntity<JsonResultEntity> testJsonReturn() { Map<String, String> map = new HashMap<>(); map.put("test", "test is success"); return ResponseEntity.ok(JsonResultUtils.success(map)); }
结果显示成功
以上是关于springboot处理统一返回json数据格式的主要内容,如果未能解决你的问题,请参考以下文章