码迷,mamicode.com
首页 > 编程语言 > 详细

springboot处理统一返回json数据格式

时间:2019-01-02 20:43:37      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:style   http   success   png   bsp   hashmap   map   实体   ima   

第一步,写一个实体类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));
}

结果显示成功

技术分享图片

 

springboot处理统一返回json数据格式

标签:style   http   success   png   bsp   hashmap   map   实体   ima   

原文地址:https://www.cnblogs.com/walblog/p/10211067.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!