1. 程式人生 > >封裝高可複用的服務端響應物件 --ServerResponse、ResponseCode

封裝高可複用的服務端響應物件 --ServerResponse、ResponseCode

在平時的編碼過程中,返回給前端的資料都會統一規範起來,用一個泛型來作為響應物件

ServerResponse

@JsonSerialize(include =  JsonSerialize.Inclusion.NON_NULL)//保證序列化json的時候,如果是null的物件,key也會消失public class ServerResponse<T> 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 = 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 <T> ServerResponse<T> createBySuccess(){         return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());    }     public static <T> ServerResponse<T> createBySuccessMessage(String msg){         return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);    }     public static <T> ServerResponse<T> createBySuccess(T data){         return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);    }     public static <T> ServerResponse<T> createBySuccess(String msg,T data){         return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);    }     public static <T> ServerResponse<T> createByError(){         return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());    }     public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){         return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);    }     public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){         return new ServerResponse<T>(errorCode,errorMessage);    }}

ResponseCode

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;    }}