1、建立枚举类
package com.example.demo.resultMap;
public enum ApiResponseStatusCode {
/** 成功*/
SUCCESS(200,"成功","success"),
FAIL(200,"失败","failure");
/** 错误代码*/
private Integer code;
/** 提示信息*/
private String message;
private String status;
private ApiResponseStatusCode(Integer code, String message,String status) {
this.code = code;
this.message = message;
this.status=status;
}
public Integer getCode() {
return this.code;
}
public String getMessage() {
return this.message;
}
public String getStatus() {
return this.status;
}
}
2、建立返回结果类
package com.example.demo.resultMap;
import lombok.Data;
@Data
public class ApiResponse<T> {
private Integer code;
private String message;
private T data;
private String status;
private ApiResponse(){
this.code = 200;
this.message = "ok";
this.data = null;
this.status="";
}
private ApiResponse(ApiResponseStatusCode apiresponsecode, T data){
this.code = apiresponsecode.getCode();
this.message = apiresponsecode.getMessage();
this.data = data;
this.status=apiresponsecode.getStatus();
}
/**
* 暴露外面静态方法. 成功
*/
public static <E> ApiResponse success(E data){
return new ApiResponse<E>(ApiResponseStatusCode.SUCCESS,data);
}
/**
* 失败
*/
public static <E> ApiResponse fail(E data){
return new ApiResponse<E>(ApiResponseStatusCode.FAIL,data);
}
}
3、控制器调用
@GetMapping("/test/xmm123")
public ApiResponse test(){
List<Map<String,String>> sqlList=new ArrayList<Map<String,String>>();
Map<String,String> testData=new HashMap<String, String>();
testData.put("name","name1");
testData.put("age","24");
sqlList.add(testData);
Map<String,String> testData1=new HashMap<String, String>();
testData1.put("name","name2");
testData1.put("age","25");
sqlList.add(testData1);
Map<String,String> testData2=new HashMap<String, String>();
testData2.put("name","name3");
testData2.put("age","26");
sqlList.add(testData2);
return ApiResponse.fail(sqlList);
}
4、结果展示