package com.zzwtec.third.common;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 草原狼
 *
 *         2017年8月17日
 */

public class ResultJsonUtil {

    private static final Logger log = LoggerFactory.getLogger(ResultJsonUtil.class);
    /**
     * 输出字符串到浏览器
     * @param obj 你要输出的 json 对象
     */
    public static boolean renderJson(HttpServletResponse response, Object obj) {
        PrintWriter pw = null;
        boolean rev = true;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            pw = response.getWriter();
            pw.write(JSONObject.toJSONString(obj));
        } catch (IOException e) {
            log.error("有异常",e);
            rev = false;
        } finally {
            if (pw != null) {
                pw.flush();
                pw.close();
            }
            return rev;
        }
    }

    /**
     * 输出文本到浏览器
     * @param content 你要输出的文本
     */
    public static boolean renderText(HttpServletResponse response, String content) {
        PrintWriter pw = null;
        boolean rev = true;
        try {
            response.setContentType("text/plain;charset=utf-8");
            pw = response.getWriter();
            pw.write(content);
        } catch (IOException e) {
            log.error("有异常",e);
            rev = false;
        } finally {
            if (pw != null) {
                pw.flush();
                pw.close();
            }
            return rev;
        }
    }
}
