前后端分离-统一返回给前端的json数据格式(RestApi)

package com.zhoujianpeng.project.response;

public class RestResponse<T> {

    private int code;
    private String msg;
    private T data;


    /**
     * 分别提供返回成功和失败的不同的方法
     * 也就是说返回的数据形式是RestResponse所包含的
     * d第一个T :泛型方法的标示,没有实际的意义
     * 第二个返回的数据类型的一种规范
     *这也就是所谓的工厂模式的应用,
     */

    public static <T> RestResponse<T> success() {
        return new RestResponse<>();
    }

    public static <T> RestResponse<T> success(T data) {
        RestResponse restResponse = new RestResponse();
        restResponse.setData(data);
        return restResponse;
    }

    public static <T> RestResponse<T> error(RestCode restCode) {
        RestResponse<T> restResponse = new RestResponse<>(restCode.code, restCode.msg);
        return restResponse;
    }

    public RestResponse() {
        //默认会调用有参的构造函数,默认是成功的
        this(RestCode.OK.code, RestCode.OK.msg);
    }

    public RestResponse(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public RestResponse(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }


    public RestResponse(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
package com.zhoujianpeng.project.response;

/**
 * 返回的code以及返回的message
 */
public enum  RestCode {

    OK(0, "OK"),
    UNKNOW_ERROR(1, "服务异常"),
    WRONG_PAGE(10100, "页码不存在"),
    ;

    RestCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public int code;
    public String msg;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}

可以参考一下别人的这个文章https://blog.csdn.net/OrangeChenZ/article/details/86468642

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值