Java Web返回JSON

來源:互聯網
上載者:User

標籤:rip   obj   content   servlet   trace   java   反序   post   text   

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 [email protected] *  */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。則輸出為falseSerializerFeature.WriteNullBooleanAsFalse,//假設List為Null。則輸出為[]SerializerFeature.WriteNullListAsEmpty,//假設Number為Null。則輸出為0SerializerFeature.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", "[email protected]");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", "[email protected]");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", "[email protected]");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", "[email protected]");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", "[email protected]");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", "[email protected]");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);}}}



Java Web返回JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.