JSONResult.java
2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.brframework.commonweb.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.brframework.commonweb.exception.HandleException;
import com.brframework.commonweb.utils.ServletUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.servlet.http.HttpServletRequest;
/**
* Created by xu on 2019-8-19 12:44:42
* REST API 数据抽象
*/
@Data
@ApiModel
public class JSONResult<T> {
//成功
public static final int DEFAULT_OK_CODE = 200;
public static final String DEFAULT_OK_MSG = "success";
//失败
public static final int DEFAULT_ERROR_CODE = 500;
public static final String DEFAULT_ERROR_MSG = "服务器异常,请稍后再试";
@ApiModelProperty(value = "code", required = true, example = "200")
private int code = 200;
@ApiModelProperty(value = "msg", required = true, example = "success")
private String msg;
@ApiModelProperty(value = "desc", required = true, example = "ok")
private String desc = "ok";
@ApiModelProperty(value = "path", required = true, example = "path/path")
private String path;
private T data;
public static JSONResult ok(){
JSONResult result = new JSONResult();
result.code = DEFAULT_OK_CODE;
result.msg = DEFAULT_OK_MSG;
result.path = ServletUtils.request().getRequestURI();
return result;
}
public static <T> JSONResult<T> ok(T data){
JSONResult<T> result = new JSONResult<>();
result.code = DEFAULT_OK_CODE;
result.msg = DEFAULT_OK_MSG;
result.path = ServletUtils.request().getRequestURI();
result.data = data;
return result;
}
public static JSONResult error(){
JSONResult result = new JSONResult();
result.code = DEFAULT_ERROR_CODE;
result.msg = DEFAULT_ERROR_MSG;
result.path = ServletUtils.request().getRequestURI();
return result;
}
public static JSONResult error(String errorMessage){
JSONResult result = new JSONResult();
result.code = DEFAULT_ERROR_CODE;
result.msg = errorMessage;
result.path = ServletUtils.request().getRequestURI();
return result;
}
public static JSONResult error(HandleException e){
JSONResult result = new JSONResult();
result.code = e.getCode();
result.msg = e.getMsg();
result.desc = e.getDesc();
result.path = ServletUtils.request().getRequestURI();
return result;
}
public static JSONResult error(Throwable throwable){
JSONResult result = new JSONResult();
result.code = DEFAULT_ERROR_CODE;
result.msg = throwable.getMessage();
result.path = ServletUtils.request().getRequestURI();
return result;
}
public String toString(){
return JSON.toJSONString(this);
}
}