自定义接口返回统一格式
package com.risen.demo.util;
import com.risen.hp.fastjson.JSONObject;
import org.springframework.http.HttpStatus;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
public class ResponseTemplate {
public static final String MSG_META = "meta";
public static final String MSG_META_RESP_CODE = "respCode";
public static final String MSG_META_RESP_MSG = "respMsg";
public static final String MSG_META_SERVICE_CODE = "serviceCode";
public static final String MSG_META_RESP_VER = "ver";
public static final String MSG_META_RESP_VERSION = "01";
public static final String RESULT_DATA = "data";
private JSONObject resultJson = new JSONObject();
private Map<String ,Object> meta = new LinkedHashMap<String ,Object>();
private Object data = new LinkedList<Object>();
protected ResponseTemplate() {
}
protected ResponseTemplate(HttpStatus status) {
init(status);
}
public static ResponseTemplate createOk(){
return new ResponseTemplate(HttpStatus.OK);
}
public static ResponseTemplate createFail(){
return new ResponseTemplate(HttpStatus.INTERNAL_SERVER_ERROR);
}
public JSONObject getResultJson(){
resultJson.put(MSG_META,meta);
resultJson.put(RESULT_DATA,data);
return this.resultJson;
}
private void init(HttpStatus status){
meta.put(MSG_META_RESP_CODE, String.valueOf(status.value()));
meta.put(MSG_META_RESP_MSG,status);
meta.put(MSG_META_SERVICE_CODE,"");
meta.put(MSG_META_RESP_VER,MSG_META_RESP_VERSION);
}
public void setServerError(String value){
meta.put(MSG_META_RESP_CODE,String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
meta.put(MSG_META_RESP_MSG,String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase() + value));
}
public void setBadRequest(String value){
meta.put(MSG_META_RESP_CODE,String.valueOf(HttpStatus.BAD_REQUEST));
meta.put(MSG_META_RESP_MSG,String.valueOf(HttpStatus.BAD_REQUEST.getReasonPhrase() + value));
}
public void setMsgMetaRespCode(String value){
meta.put(MSG_META_RESP_CODE, value);
}
public String getMsgMetaRespCode(String value){
return (String) meta.get(MSG_META_RESP_CODE);
}
public void setMsgMetaRespMsg(String value){
meta.put(MSG_META_RESP_MSG,value);
}
public String getMsgMetaRespMsg(){
return (String) meta.get(MSG_META_RESP_MSG);
}
public void setMsgMetaServiceCode(String value){
meta.put(MSG_META_SERVICE_CODE,value);
}
public String getMsgMetaServiceCode(){
return (String) meta.get(MSG_META_SERVICE_CODE);
}
public void setMsgMetaRespVer(String value){
meta.put(MSG_META_RESP_VER,value);
}
public String getMsgMetaRespVer(){
return (String) meta.get(MSG_META_RESP_VER);
}
public void setResultData(Object valueData){
this.data = valueData;
}
public Object getResultData(){
return this.data;
}
}