高复用服务端响应对象

之所以不用public构造,是因为出现既匹配msg,又匹配data的构造函数,只能为msg的问题


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * @author zhoupeng
 */
@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, String msg) {
        this.status = status;
        this.msg = msg;
    }

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


    public static <T> ServerResponse success(int status) {
        return new ServerResponse(status);
    }

    public static <T> ServerResponse<T> success(String msg) {
        return new ServerResponse<>(ResponseStatus.SUCCESS.getCode(), msg);
    }

    public static <T> ServerResponse<T> success(T data) {
        return new ServerResponse<>(ResponseStatus.SUCCESS.getCode(), data);
    }

    public static <T> ServerResponse<T> success(String msg, T data) {
        return new ServerResponse<>(ResponseStatus.SUCCESS.getCode(), msg, data);
    }


    @JsonIgnore
    //使之不再序列化到json中
    public boolean isSuccess() {
        return this.status == ResponseStatus.SUCCESS.getCode();
    }


    public static <T> ServerResponse<T> error(int errorCode) {
        return new ServerResponse<>(errorCode);
    }

    public static <T> ServerResponse<T> error(String errorMessage) {
        return new ServerResponse<>(ResponseStatus.ERROR.getCode(), errorMessage);
    }

    public static <T> ServerResponse<T> error(int errorCode, String errorMessage) {
        return new ServerResponse<>(errorCode, errorMessage);
    }

    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }
}




类注解可替换为:

@JsonInclude(JsonInclude.Include.NON_NULL)

你可能感兴趣的:(javaWeb入门)