1. 程式人生 > >springboot處理統一返回json資料格式

springboot處理統一返回json資料格式

第一步,寫一個實體類JsonResultEntity,定義返回的引數

package com.bujiang.magic.common.utils;

public class JsonResultEntity {
    private Object data;
    private String message;
    private Integer code;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this
.data = data; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }

第二步,寫一個工具類ResponseEntity

package com.bujiang.magic.common.utils;

public class JsonResultUtils{

    public static JsonResultEntity success(Object object) {
        JsonResultEntity jsonResult = new JsonResultEntity();
        jsonResult.setData(object);
        jsonResult.setCode(200);
        jsonResult.setMessage(
"success"); return jsonResult; } public static JsonResultEntity success(Object object, Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setData(object); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } public static JsonResultEntity success() { return success(null); } public static JsonResultEntity error(Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } public static JsonResultEntity success(Integer code, String message) { JsonResultEntity jsonResult = new JsonResultEntity(); jsonResult.setCode(code); jsonResult.setMessage(message); return jsonResult; } }

第三步,測試

DemoController:

@ApiOperation(value = "測試統一json返回", notes = "")
@RequestMapping(value = "testJsonReturn", method = RequestMethod.POST)
public ResponseEntity<JsonResultEntity> testJsonReturn() {
    return userService.testJsonReturn();
}

UserService:

/**
 * 測試json統一返回資料
 * @return
 */
ResponseEntity<JsonResultEntity> testJsonReturn();

UserServiceImpl

@Override
public ResponseEntity<JsonResultEntity> testJsonReturn() {
    Map<String, String> map = new HashMap<>();
    map.put("test", "test is success");
    return ResponseEntity.ok(JsonResultUtils.success(map));
}

結果顯示成功