在用户模块开发过程中经常要想前台传递数据信息,假设这个json格式是这样的
{
state:0,
msg:"success",
data:{一堆不同类型的数据}
}
每次弄不同的东西的话,很烦。为了实现这个功能就设计了一个高复用的接口类ServiceResponse,并将其json序列化:
package com.mmal.common;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.omg.CORBA.Object;
import java.io.Serializable;
/**
* Created by Administrator on 2017/9/4.
*/
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保证序列化json的时候,如果是null,key也会消失
public class ServiceResponse <T> implements Serializable {
private int status;
private String msg;
private T data;
private ServiceResponse(int status){
this.status=status;
}
private ServiceResponse(int status,T data){
this.status =status;
this.data=data;
}
private ServiceResponse(int status,String msg,T data){
this.status =status;
this.msg =msg;
this.data = data;
}
private ServiceResponse(int status,String msg){
this.status =status;
this.msg=msg;
}
@JsonIgnore
//使之不在序列化结果之中
public boolean isSucess(){
return this.status==ResponseCode.SUCCESS.getCode();
}
public int getStatus(){
return status;
}
public String getMsg(){
return msg;
}
public T getData(){
return data;
}
public static <T> ServiceResponse<T> CreateBySuccess(){
return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServiceResponse<T> CreateBySuccessMessage(String msg){
return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
}
public static <T> ServiceResponse<T> CreateBySuccess(T data){
return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),data);
}
public static <T> ServiceResponse<T> CreateBySuccess(String msg,T data){
return new ServiceResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static <T> ServiceResponse<T> CreateByError(){
return new ServiceResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static <T> ServiceResponse<T> CreateByErrorMessage(String errormsg){
return new ServiceResponse<T>(ResponseCode.ERROR.getCode(),errormsg);
}
//报一个变量的错误
public static <T> ServiceResponse<T> CreateByErrorCodeMessage(int errorCode,String errorMessage){
return new ServiceResponse<T>(errorCode,errorMessage);
}
}
同时还需要一个枚举类ResponseCode:
package com.mmal.common;
/**
* Created by Administrator on 2017/9/4.
*/
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEAGAL_ARGUMENT(2,"ILLEAGAL_ARGUMENT");
private final int code;
private final String desc;
private ResponseCode(int code,String desc){
this.code = code;
this.desc=desc;
}
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}