SpringBoot:如何优雅地进行参数传递、响应数据封装

import com.alibaba.fastjson.JSONObject;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/**@author guozhengMu@version 1.
摘要由CSDN通过智能技术生成

import com.alibaba.fastjson.JSONObject;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

/**

  • @author guozhengMu

  • @version 1.0

  • @date 2019/8/21 14:55

  • @description

  • @modify

*/

@RestController

@RequestMapping(value = “/test”, method = RequestMethod.GET)

public class TestController {

@RequestMapping(“/json”)

public JSONObject test() {

JSONObject result = new JSONObject();

try {

// 业务逻辑代码

result.put(“code”, 0);

result.put(“msg”, “操作成功!”);

result.put(“data”, “测试数据”);

} catch (Exception e) {

result.put(“code”, 500);

result.put(“msg”, “系统异常,请联系管理员!”);

}

return result;

}

}

这样的话,每个接口都这样处理,非常麻烦,需要一种更优雅的实现方式

2.1 定义统一的JSON结构

===============

统一的 JSON 结构中属性包括数据、状态码、提示信息,其他项可以自己根据需要添加。一般来说,应该有默认的返回结构,也应该有用户指定的返回结构。由于返回数据类型无法确定,需要使用泛型,代码如下:

public class ResponseInfo {

/**

  • 状态码

*/

protected String code;

/**

  • 响应信息

*/

protected String msg;

/**

  • 返回数据

*/

private T data;

/**

  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值