Web項目中經常涉及到AJAX請求返回JSON和JSONP數據。JSON數據在server端和瀏覽器端傳輸,本質上就是傳輸字符串,只是這個字符串符合JSON語法格式。瀏覽器端會依照普通文本的格式接收JSON字符串。終於JSON字符串轉成JSON對象通過JavaScript實現。眼下部分瀏覽器(IE9下面瀏覽器沒有提供)和經常使用的JS庫都提供了JSON序列化和反序列化的方法。如jQuery的AJAX請求能夠指定返回的數據格式,包含text、json、jsonp、xml、html等。
Webserver端僅僅要把Java對象數據轉成JSON字符串。並把JSON字符串以文本的形式通過response輸出就可以。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
* Web服務端返回JSON工具類
* 工具類依賴FastJSON
* 工具類支持返回JSON和JSONP格式數據
* @author accountwcx@qq.com
*
*/
public class ResponseJsonUtils {
/**
* 默認字符編碼
*/
private static String encoding = "UTF-8";
/**
* JSONP默認的回調函數
*/
private static String callback = "callback";
/**
* FastJSON的序列化設置
*/
private static SerializerFeature[] features = new SerializerFeature[]{
//輸出Map中為Null的值
SerializerFeature.WriteMapNullValue,
//假設Boolean對象為Null。則輸出為false
SerializerFeature.WriteNullBooleanAsFalse,
//假設List為Null。則輸出為[]
SerializerFeature.WriteNullListAsEmpty,
//假設Number為Null。則輸出為0
SerializerFeature.WriteNullNumberAsZero,
//輸出Null字符串
SerializerFeature.WriteNullStringAsEmpty,
//格式化輸出日期
SerializerFeature.WriteDateUseDateFormat
};
/**
* 把Java對象JSON序列化
* @param obj 須要JSON序列化的Java對象
* @return JSON字符串
*/
private static String toJSONString(Object obj){
return JSON.toJSONString(obj, features);
}
/**
* 返回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);
PrintWriter out = null;
try{
out = response.getWriter();
out.write(toJSONString(data));
out.flush();
}catch(IOException e){
e.printStackTrace();
}
}
/**
* 返回JSON格式數據,使用默認編碼
* @param response
* @param data 待返回的Java對象
*/
public static void json(HttpServletResponse response, Object data){
json(response, data, encoding);
}
/**
* 返回JSONP數據,使用默認編碼和默認回調函數
* @param response
* @param data JSONP數據
*/
public static void jsonp(HttpServletResponse response, Object data){
jsonp(response, callback, data, encoding);
}
/**
* 返回JSONP數據,使用默認編碼
* @param response
* @param callback JSONP回調函數名稱
* @param data JSONP數據
*/
public static void jsonp(HttpServletResponse response, String callback, Object data){
jsonp(response, callback, data, encoding);
}
/**
* 返回JSONP數據
* @param response
* @param callback JSONP回調函數名稱
* @param data JSONP數據
* @param encoding JSONP數據編碼
*/
public static void jsonp(HttpServletResponse response, String callback, Object data, String encoding){
StringBuffer sb = new StringBuffer(callback);
sb.append("(");
sb.append(toJSONString(data));
sb.append(");");
// 設置編碼格式
response.setContentType("text/plain;charset=" + encoding);
response.setCharacterEncoding(encoding);
PrintWriter out = null;
try {
out = response.getWriter();
out.write(sb.toString());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getEncoding() {
return encoding;
}
public static void setEncoding(String encoding) {
ResponseJsonUtils.encoding = encoding;
}
public static String getCallback() {
return callback;
}
public static void setCallback(String callback) {
ResponseJsonUtils.callback = callback;
}
}
/**
* 在Servlet返回JSON數據
*/
@WebServlet("/json.do")
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 7500835936131982864L;
/**
* 返回json格式數據
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
ResponseJsonUtils.json(response, data);
}
}
/**
* Servlet返回JSONP格式數據
*/
@WebServlet("/jsonp.do")
public class JsonpServlet extends HttpServlet {
private static final long serialVersionUID = -8343408864035108293L;
/**
* 請求會發送callback參數作為回調函數,假設沒有發送callback參數則使用默認回調函數
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//client發送的回調函數
String callback = request.getParameter("callback");
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
if(callback == null || callback.length() == 0){
//假設client沒有發送回調函數。則使用默認的回調函數
ResponseJsonUtils.jsonp(response, data);
}else{
//使用client的回調函數
ResponseJsonUtils.jsonp(response, callback, data);
}
}
}
/**
* 在Struts2中返回JSON和JSONP
*/
public class JsonAction extends ActionSupport {
private static final long serialVersionUID = 5391000845385666048L;
/**
* JSONP的回調函數
*/
private String callback;
/**
* 返回JSON
*/
public void json(){
HttpServletResponse response = ServletActionContext.getResponse();
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
ResponseJsonUtils.json(response, data);
}
/**
* 返回JSONP
*/
public void jsonp(){
HttpServletResponse response = ServletActionContext.getResponse();
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
if(callback == null || callback.length() == 0){
//假設client沒有發送回調函數,則使用默認的回調函數
ResponseJsonUtils.jsonp(response, data);
}else{
//使用client的回調函數
ResponseJsonUtils.jsonp(response, callback, data);
}
}
public String getCallback() {
return callback;
}
public void setCallback(String callback) {
this.callback = callback;
}
}
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Spring MVC返回JSON和JSONP數據
*/
@Controller
@RequestMapping("/json")
public class JsonController {
/**
* 返回JSON數據
* @param request
* @param response
*/
@RequestMapping("/json.do")
public void json(HttpServletRequest request, HttpServletResponse response){
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
ResponseJsonUtils.json(response, data);
}
/**
* 返回JSONP數據
* @param callback JSONP的回調函數
* @param request
* @param response
*/
@RequestMapping("/jsonp.do")
public void json(String callback, HttpServletRequest request, HttpServletResponse response){
Map<String, Object> data = new HashMap<String, Object>();
data.put("date", new Date());
data.put("email", "accountwcx@qq.com");
data.put("age", 30);
data.put("name", "csdn");
data.put("array", new int[]{1,2,3,4});
if(callback == null || callback.length() == 0){
//假設client沒有發送回調函數,則使用默認的回調函數
ResponseJsonUtils.jsonp(response, data);
}else{
//使用client的回調函數
ResponseJsonUtils.jsonp(response, callback, data);
}
}
}
