wang-hao-jie
2021-11-09 6f81429892b6e751056ba250a19a6ecf746fa729
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
package cn.exrick.xboot.core.common.utils;
 
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
 
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
 
/**
 * @author Exrickx
 */
@Slf4j
public class ResponseUtil {
 
    /**
     * 使用response输出JSON
     * @param response
     * @param resultMap
     */
    public static void out(HttpServletResponse response, Map<String, Object> resultMap) {
 
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getOutputStream().write(new Gson().toJson(resultMap).getBytes());
        } catch (Exception e) {
            log.error(e + ",输出JSON出错");
        }
    }
 
    public static Map<String, Object> resultMap(boolean flag, Integer code, String msg) {
 
        return resultMap(flag, code, msg, null);
    }
 
    public static Map<String, Object> resultMap(boolean flag, Integer code, String msg, Object data) {
 
        Map<String, Object> resultMap = new HashMap<String, Object>(16);
        resultMap.put("success", flag);
        resultMap.put("message", msg);
        resultMap.put("code", code);
        resultMap.put("timestamp", System.currentTimeMillis());
        if (data != null) {
            resultMap.put("result", data);
        }
        return resultMap;
    }
}