package com.bcxin.ars.rest.util;

import com.alibaba.fastjson.JSON;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author linqinglin
 * @date 2020/06/05 0005 10:34
 */
public class ResponseJsonUtils {
    public ResponseJsonUtils() {
    }

    public static boolean isJsonAccept(NativeWebRequest request) {
        return request.getHeader("accept").indexOf("application/json") > -1 || request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1;
    }

    public static boolean isJsonAccept(HttpServletRequest request) {
        return request.getHeader("accept").indexOf("application/json") > -1 || request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1;
    }

    public static void writeJSON(ServletResponse response, String json) {
        try {
            response.setContentType("application/json; charset=UTF-8");
            writeJSON(response.getWriter(), json);
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }

    public static void writeJSON(PrintWriter wirter, String json) {
        wirter.print(json);
        wirter.flush();
        wirter.close();
    }

    public static void writeJSON(ServletResponse response, Object json) {
        try {
            response.setContentType("application/json; charset=UTF-8");
            writeJSON(response.getWriter(), json);
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }

    public static void writeJSON(PrintWriter wirter, Object json) {
        wirter.print(JSON.toJSONString(json));
        wirter.flush();
        wirter.close();
    }
}
