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;
/**
- 若