springboot 定义统一的返回json渲染格式
Posted 健康平安的活着
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 定义统一的返回json渲染格式相关的知识,希望对你有一定的参考价值。
一 实操案例
1.定义map类型
package com.ljf.spring.boot.demo.common;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @ClassName: R
* @Description: TODO
* @Author: liujianfu
* @Date: 2022/12/03 15:53:28
* @Version: V1.0
**/
public class R
private Boolean success;
private Integer code;
private String message;
private Map<String, Object> data = new LinkedHashMap<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;
public Boolean getSuccess()
return success;
public void setSuccess(Boolean success)
this.success = success;
public Integer getCode()
return code;
public void setCode(Integer code)
this.code = code;
public String getMessage()
return message;
public void setMessage(String message)
this.message = message;
public Map<String, Object> getData()
return data;
public void setData(Map<String, Object> data)
this.data = data;
2.定义错误编码
package com.ljf.spring.boot.demo.common;
public interface ResultCode
public static Integer SUCCESS = 20000; //成功
public static Integer ERROR = 20001; //失败
3.使用
@ResponseBody
@GetMapping("/allMp")
public R findAllUserByMp(
@RequestParam(name = "pageNum", required = false, defaultValue = "1")
int pageNum,
@RequestParam(name = "pageSize", required = false, defaultValue = "10")
int pageSize)
System.out.println("进入查询......");
return R.ok().data("items",userService.queryAllUserByMp(pageNum,pageSize));
4.效果
以上是关于springboot 定义统一的返回json渲染格式的主要内容,如果未能解决你的问题,请参考以下文章