SpringBoot 接口返回数据格式统一

开发工具:

        IDEA 2022.1.4

目录

1. 概述

2. 定义返回格式实体类Result,实现Serializable接口

3. 测试: 登录操作

4. 结语


1. 概述

        在工作中,经常对接三方的web服务,服务返回统一的json数据格式,也就是说,服务有自身的一套json返回标准。感觉挺好。在网上查找资料,在自己的web服务中,想实现下。

        一般的json返回,首先想到code、message、timestamp、data、result等信息。针对code,在web服务定义,针对成功、失败、异常等,返回不同值,message给出对应的描述信息。timestamp返回时间戳,data、result返回数据集等信息。在此基础上,可能会有其他的扩展数据。

        按此思路,进行实现。

2. 定义返回格式实体类Result<T>,实现Serializable接口

        success方法用于更新操作;

        ok方法用于更新操作和返回数据集;

        error方法用于返回错误和异常。

@Data
public class Result<T> implements Serializable {
    private static final long serialVersionUID= 1L;

    private int code=0;
    private String message= "操作成功!";
    private boolean success= true;
    private long timestamp= System.currentTimeMillis();
    private T result;


    public Result(){

    }

    /*
    * 返回成功 success message code
    * */
    public Result<T> success(String message){
        this.message= message;
        this.code= 200;
        this.success= true;
        return this;
    }

    /*
     * 返回成功 success message code = result
     * */
    public static Result<Object> ok(String message){
        Result<Object> result1= new Result<Object>();
        result1.setSuccess(true);
        result1.setCode(200);
        result1.setMessage(message);
        return result1;
    }

    /*
     * 带数据集 返回成功 success code result= result
     * */
    public static Result<Object> ok(Object data){
        Result<Object> result1= new Result<Object>();
        result1.setSuccess(true);
        result1.setCode(200);
        result1.setResult(data);
        return result1;
    }

    /*
     * 返回成功 success message code= result
     * */
    public Result<T> error500(String message){
        this.message= message;
        this.code= 500;
        this.success= false;
        return this;
    }

    public static Result<Object> error(int code, String message){
        Result<Object> result1= new Result<Object>();
        result1.setCode(code);
        result1.setMessage(message);
        result1.setSuccess(false);
        return result1;
    }
    //异常返回500    
    public static Result<Object> error(String message){
        return error(500, message);
    }

}

3. 测试: 登录操作

        登录操作获取token演示获取json返回格式

@PostMapping("/user/login")
    public Result<?> login(@RequestBody User user){
        SqlSession sqlSession= null;
        Map<String, Object> map= new HashMap<>();
        try{
            sqlSession= MybatisUtils.getSqlSession();
            UserMapper mapper= sqlSession.getMapper(UserMapper.class);
            user= mapper.login(user);
            if (user!= null){
                //生成token
                Map<String, String> tokenmap= new HashMap<>();
                tokenmap.put("username", user.getUsername());
                tokenmap.put("password", user.getPassword());
                String token= JwtUtils.getToken(tokenmap);
                //返回数据
                map.put("user", user);
                map.put("token", token);
                return Result.ok(map);
            } else {
                return Result.error(201, "用户不存在!");
            }
        } catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"异常!"+ e.getMessage());
        } finally {
            if (sqlSession!= null){
                sqlSession.close();
            }
        }
    }

        返回数据如下:

{
    "code": 200,
    "message": "操作成功!",
    "success": true,
    "timestamp": 1679062301192,
    "result": {
        "user": {
            "id": 1,
            "loginname": "ceaning",
            "username": "国士无双",
            "password": "123qwe,.",
            "groupid": "G001",
            "memo": "ceaning",
            "enable": 1
        },
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyM3F3ZSwuIiwibG9naW5uYW1lIjoiY2VhbmluZyIsImV4cCI6MTY3OTA2OTUwMX0.KX8Ttlj46CGikAk_vYZk06nVHMBVBcNsc5eaO0e1sEQ"
    }
}

4. 结语

        感谢网上大佬分享经验,让人受益匪浅。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值