公共接口返回数据的封装

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;

public class R extends HashMap {
	private static final long serialVersionUID = 1L;
	
	public R() {
		put("resultCode", 0);
		put("success", true);
		put("resultMessage", "");
	}
	
	public static R error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
	}
	
	public static R err( Map map) {
		return err(HttpStatus.SC_INTERNAL_SERVER_ERROR, map);
	}
	
	public static R error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	public static R error(Map map) {
		Object code = map.get("resultCode");
		Object desc = map.put("success",false);
		Object msg = map.get("resultMessage");
		if(code == null){
			code = HttpStatus.SC_INTERNAL_SERVER_ERROR;
		}
		if(desc == null||StringUtils.isEmpty(desc.toString())){
			if(msg == null||StringUtils.isEmpty(msg.toString())){
				desc = "接口调用失败";
			}else{
				desc = msg;
			}
		}
		return error(Integer.valueOf(code.toString()),desc.toString());
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("resultCode", code);
		r.put("success",false);
		r.put("msg", msg);
		return r;
	}
	
	public static R err(int code,Map map) {
		R r = new R();
		r.put("code", code);
		r.put("success",false);
		r.putAll(map);
		r.put("resultMessage", "未知异常,请联系管理员");
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put("result",msg);
		return r;
	}
	
	public static R ok(Map map) {
		R r = new R();
		r.put("result",map);
		return r;
	}
	
	
	
	public static R ok() {
		return new R();
	}

	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}
}

 

你可能感兴趣的:(公共接口返回数据的封装)