cn.yangjunda.util.ResponseJsonUtil Maven / Gradle / Ivy
package cn.yangjunda.util;
import org.codehaus.jackson.map.ObjectMapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
/**
* Created by juanda on 12/6/17.
*/
public class ResponseJsonUtil {
/**
* 默认字符编码
*/
private static String encoding = "UTF-8";
/**
* JSONP默认的回调函数
*/
private static String callback = "callback";
/**
* 返回jackson JSON格式数据
* @param response
* @param data 待返回的Java对象
* @param encoding 返回JSON字符串的编码格式
*/
public static void json(HttpServletResponse response, Object data, String encoding){
//设置编码格式
response.setContentType("text/plain;charset=" + encoding);
response.setCharacterEncoding(encoding);
ObjectMapper mapper = new ObjectMapper();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(sdf);
PrintWriter out = null;
try{
String outJson = mapper.writeValueAsString(data);
out = response.getWriter();
out.write(outJson);
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 返回Jackson JSON格式数据,使用默认编码 UTF-8
* @param response
* @param data 待返回的Java对象
*/
public static void json(HttpServletResponse response, Object data){
json(response, data, encoding);
}
public static String getEncoding() {
return encoding;
}
public static void setEncoding(String encoding) {
ResponseJsonUtil.encoding = encoding;
}
public static String getCallback() {
return callback;
}
public static void setCallback(String callback) {
ResponseJsonUtil.callback = callback;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy