rest接口会返回各种各样的数据,如果对接口的格式不加约束,很容易造成混乱。
在实际项目中,一般会把结果放在一个封装类中,封装类中包含http状态值,状态消息,以及实际的数据。这里主要记录两种方式:(效果如下)
1、采用Map对象作为返回对象。
public static Map<String, Object> getResponse(Object object, String msgSuccess, String msgFailed, boolean isOperate) {
Map<String, Object> data = new HashMap<>();
if (object != null) {
data.put("success", true);
data.put("msg", msgSuccess);
data.put("result", 1);
} else {
data.put("success", false);
data.put("msg", msgFailed);
data.put("result", 0);
}
if (!isOperate) {
data.put("data", object);
} else {
data.put("data", null);
}
return data;
}
2、根据不同类型结果,调用不同的封装方法。
@SuppressWarnings("unchecked")
public static <T> Tb_Response<T> getResponse(List<T> objectList, String msgSuccess, String msgFailed) {
Tb_Response<T> tb_Response = new Tb_Response<T>();
if (objectList.size() > 0) {
tb_Response.setSuccess(true);
tb_Response.setMsg(msgSuccess);
tb_Response.setResult(1);
tb_Response.setData((List<T>) objectList);
} else {
tb_Response.setSuccess(false);
tb_Response.setMsg(msgFailed);
tb_Response.setResult(0);
}
return (Tb_Response<T>) tb_Response;
}
@SuppressWarnings("unchecked")
public static <T> Tb_ResponseData<T> getResponseData(T object, String msgSuccess, String msgFailed) {
Tb_ResponseData<T> tb_ResponseData = new Tb_ResponseData<T>();
if (object != null) {
tb_ResponseData.setSuccess(true);
tb_ResponseData.setMsg(msgSuccess);
tb_ResponseData.setResult(1);
tb_ResponseData.setData((T) object);
} else {
tb_ResponseData.setSuccess(false);
tb_ResponseData.setMsg(msgFailed);
tb_ResponseData.setResult(0);
tb_ResponseData.setData(null);
}
return (Tb_ResponseData<T>) tb_ResponseData;
}
public static Tb_ResponseData<Boolean> getResponseData(boolean result, String msgSuccess, String msgFailed) {
Tb_ResponseData<Boolean> tb_ResponseData = new Tb_ResponseData<Boolean>();
if (result) {
tb_ResponseData.setSuccess(true);
tb_ResponseData.setMsg(msgSuccess);
tb_ResponseData.setResult(1);
} else {
tb_ResponseData.setSuccess(false);
tb_ResponseData.setMsg(msgFailed);
tb_ResponseData.setResult(0);
}
tb_ResponseData.setData(null);
return tb_ResponseData;
}
到此这篇关于SpringBoot接口返回结果封装方法的文章就介绍到这了,更多相关SpringBoot接口封装内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!