常用后端返回前端数据格式封装类

ServerResponse.java

package com.my.oasystem.common; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.io.Serializable; @JsonSerialize(include =JsonSerialize.Inclusion.NON_NULL) //保证序列化json的时候,如果是null的对象,key也会消失 public class ServerResponse implements Serializable {private int status; private String msg; private T data; private ServerResponse(int status){ this.status = status; } private ServerResponse(int status, T data){ this.status = status; this.data = https://www.it610.com/article/data; }private ServerResponse(int status, String msg, T data){ this.status = status; this.msg = msg; this.data = data; }private ServerResponse(int status, String msg){ this.status = status; this.msg = msg; }@JsonIgnore //使之不在json序列化结果当中 public boolean isSuccess(){ return this.status == ResponseCode.SUCCESS.getCode(); }public int getStatus(){ return status; } public T getData(){ return data; } public String getMsg(){ return msg; }public static ServerResponse createBySuccess(){ return new ServerResponse(ResponseCode.SUCCESS.getCode()); }public static ServerResponse createBySuccessMessage(String msg){ return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg); }public static ServerResponse createBySuccess(T data){ return new ServerResponse(ResponseCode.SUCCESS.getCode(),data); }public static ServerResponse createBySuccess(String msg,T data){ return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg,data); }public static ServerResponse createByError(){ return new ServerResponse(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc()); }public static ServerResponse createByErrorMessage(String errorMessage){ return new ServerResponse(ResponseCode.ERROR.getCode(),errorMessage); }public static ServerResponse createByErrorCodeMessage(int errorCode,String errorMessage){ return new ServerResponse(errorCode,errorMessage); }}

【常用后端返回前端数据格式封装类】ResponseCode.java
package com.my.oasystem.common; public enum ResponseCode {SUCCESS(0,"SUCCESS"), ERROR(1,"ERROR"), NEED_LOGIN(10,"NEED_LOGIN"), ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT"); private final int code; private final String desc; ResponseCode(int code, String desc){ this.code = code; this.desc = desc; }public int getCode(){ return code; } public String getDesc(){ return desc; }}

    推荐阅读