在项目开发中,接口与接口之间、前后端之间的数据传输都使用 JSON 格式。
fastjson使用
阿里巴巴的 fastjson是目前应用最广泛的JSON解析框架。本文也将使用fastjson。
1.1 引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.35</version>
</dependency>
2 统一封装返回数据
在web项目中,接口返回数据一般要包含状态码、信息、数据等,例如下面的接口示例:
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<T> {
/**
* 状态码
*/
protected String code;
/**
* 响应信息
*/
protected String msg;
/**
* 返回数据
*/
private T data;
/**
* 若没有数据返回,默认状态码为 0,提示信息为“操作成功!”
*/
public ResponseInfo() {
this.code = 0;
this.msg = "操作成功!";
}
/**
*