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输出就可以。

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3.  
  4. import javax.servlet.http.HttpServletResponse;
  5.  
  6. import com.alibaba.fastjson.JSON;
  7. import com.alibaba.fastjson.serializer.SerializerFeature;
  8.  
  9. /**
  10. *
  11. * Web服务端返回JSON工具类
  12. * 工具类依赖FastJSON
  13. * 工具类支持返回JSON和JSONP格式数据
  14. * @author accountwcx@qq.com
  15. *
  16. */
  17. public class ResponseJsonUtils {
  18. /**
  19. * 默认字符编码
  20. */
  21. private static String encoding = "UTF-8";
  22.  
  23. /**
  24. * JSONP默认的回调函数
  25. */
  26. private static String callback = "callback";
  27.  
  28. /**
  29. * FastJSON的序列化设置
  30. */
  31. private static SerializerFeature[] features = new SerializerFeature[]{
  32. //输出Map中为Null的值
  33. SerializerFeature.WriteMapNullValue,
  34.  
  35. //假设Boolean对象为Null。则输出为false
  36. SerializerFeature.WriteNullBooleanAsFalse,
  37.  
  38. //假设List为Null。则输出为[]
  39. SerializerFeature.WriteNullListAsEmpty,
  40.  
  41. //假设Number为Null。则输出为0
  42. SerializerFeature.WriteNullNumberAsZero,
  43.  
  44. //输出Null字符串
  45. SerializerFeature.WriteNullStringAsEmpty,
  46.  
  47. //格式化输出日期
  48. SerializerFeature.WriteDateUseDateFormat
  49. };
  50.  
  51. /**
  52. * 把Java对象JSON序列化
  53. * @param obj 须要JSON序列化的Java对象
  54. * @return JSON字符串
  55. */
  56. private static String toJSONString(Object obj){
  57. return JSON.toJSONString(obj, features);
  58. }
  59.  
  60. /**
  61. * 返回JSON格式数据
  62. * @param response
  63. * @param data 待返回的Java对象
  64. * @param encoding 返回JSON字符串的编码格式
  65. */
  66. public static void json(HttpServletResponse response, Object data, String encoding){
  67. //设置编码格式
  68. response.setContentType("text/plain;charset=" + encoding);
  69. response.setCharacterEncoding(encoding);
  70.  
  71. PrintWriter out = null;
  72. try{
  73. out = response.getWriter();
  74. out.write(toJSONString(data));
  75. out.flush();
  76. }catch(IOException e){
  77. e.printStackTrace();
  78. }
  79. }
  80.  
  81. /**
  82. * 返回JSON格式数据,使用默认编码
  83. * @param response
  84. * @param data 待返回的Java对象
  85. */
  86. public static void json(HttpServletResponse response, Object data){
  87. json(response, data, encoding);
  88. }
  89.  
  90. /**
  91. * 返回JSONP数据,使用默认编码和默认回调函数
  92. * @param response
  93. * @param data JSONP数据
  94. */
  95. public static void jsonp(HttpServletResponse response, Object data){
  96. jsonp(response, callback, data, encoding);
  97. }
  98.  
  99. /**
  100. * 返回JSONP数据,使用默认编码
  101. * @param response
  102. * @param callback JSONP回调函数名称
  103. * @param data JSONP数据
  104. */
  105. public static void jsonp(HttpServletResponse response, String callback, Object data){
  106. jsonp(response, callback, data, encoding);
  107. }
  108.  
  109. /**
  110. * 返回JSONP数据
  111. * @param response
  112. * @param callback JSONP回调函数名称
  113. * @param data JSONP数据
  114. * @param encoding JSONP数据编码
  115. */
  116. public static void jsonp(HttpServletResponse response, String callback, Object data, String encoding){
  117. StringBuffer sb = new StringBuffer(callback);
  118. sb.append("(");
  119. sb.append(toJSONString(data));
  120. sb.append(");");
  121.  
  122. // 设置编码格式
  123. response.setContentType("text/plain;charset=" + encoding);
  124. response.setCharacterEncoding(encoding);
  125.  
  126. PrintWriter out = null;
  127. try {
  128. out = response.getWriter();
  129. out.write(sb.toString());
  130. out.flush();
  131. } catch (IOException e) {
  132. e.printStackTrace();
  133. }
  134. }
  135.  
  136. public static String getEncoding() {
  137. return encoding;
  138. }
  139.  
  140. public static void setEncoding(String encoding) {
  141. ResponseJsonUtils.encoding = encoding;
  142. }
  143.  
  144. public static String getCallback() {
  145. return callback;
  146. }
  147.  
  148. public static void setCallback(String callback) {
  149. ResponseJsonUtils.callback = callback;
  150. }
  151. }
  1. /**
  2. * 在Servlet返回JSON数据
  3. */
  4. @WebServlet("/json.do")
  5. public class JsonServlet extends HttpServlet {
  6. private static final long serialVersionUID = 7500835936131982864L;
  7.  
  8. /**
  9. * 返回json格式数据
  10. */
  11. protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. Map<String, Object> data = new HashMap<String, Object>();
  13.  
  14. data.put("date", new Date());
  15. data.put("email", "accountwcx@qq.com");
  16. data.put("age", 30);
  17. data.put("name", "csdn");
  18. data.put("array", new int[]{1,2,3,4});
  19.  
  20. ResponseJsonUtils.json(response, data);
  21. }
  22. }
  1. /**
  2. * Servlet返回JSONP格式数据
  3. */
  4. @WebServlet("/jsonp.do")
  5. public class JsonpServlet extends HttpServlet {
  6. private static final long serialVersionUID = -8343408864035108293L;
  7.  
  8. /**
  9. * 请求会发送callback參数作为回调函数,假设没有发送callback參数则使用默认回调函数
  10. */
  11. protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  12. //client发送的回调函数
  13. String callback = request.getParameter("callback");
  14.  
  15. Map<String, Object> data = new HashMap<String, Object>();
  16.  
  17. data.put("date", new Date());
  18. data.put("email", "accountwcx@qq.com");
  19. data.put("age", 30);
  20. data.put("name", "csdn");
  21. data.put("array", new int[]{1,2,3,4});
  22.  
  23. if(callback == null || callback.length() == 0){
  24. //假设client没有发送回调函数。则使用默认的回调函数
  25. ResponseJsonUtils.jsonp(response, data);
  26. }else{
  27. //使用client的回调函数
  28. ResponseJsonUtils.jsonp(response, callback, data);
  29. }
  30. }
  31. }
  1. /**
  2. * 在Struts2中返回JSON和JSONP
  3. */
  4. public class JsonAction extends ActionSupport {
  5. private static final long serialVersionUID = 5391000845385666048L;
  6.  
  7. /**
  8. * JSONP的回调函数
  9. */
  10. private String callback;
  11.  
  12. /**
  13. * 返回JSON
  14. */
  15. public void json(){
  16. HttpServletResponse response = ServletActionContext.getResponse();
  17.  
  18. Map<String, Object> data = new HashMap<String, Object>();
  19.  
  20. data.put("date", new Date());
  21. data.put("email", "accountwcx@qq.com");
  22. data.put("age", 30);
  23. data.put("name", "csdn");
  24. data.put("array", new int[]{1,2,3,4});
  25.  
  26. ResponseJsonUtils.json(response, data);
  27. }
  28.  
  29. /**
  30. * 返回JSONP
  31. */
  32. public void jsonp(){
  33. HttpServletResponse response = ServletActionContext.getResponse();
  34.  
  35. Map<String, Object> data = new HashMap<String, Object>();
  36.  
  37. data.put("date", new Date());
  38. data.put("email", "accountwcx@qq.com");
  39. data.put("age", 30);
  40. data.put("name", "csdn");
  41. data.put("array", new int[]{1,2,3,4});
  42.  
  43. if(callback == null || callback.length() == 0){
  44. //假设client没有发送回调函数,则使用默认的回调函数
  45. ResponseJsonUtils.jsonp(response, data);
  46. }else{
  47. //使用client的回调函数
  48. ResponseJsonUtils.jsonp(response, callback, data);
  49. }
  50. }
  51.  
  52. public String getCallback() {
  53. return callback;
  54. }
  55.  
  56. public void setCallback(String callback) {
  57. this.callback = callback;
  58. }
  59. }
  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3.  
  4. /**
  5. * Spring MVC返回JSON和JSONP数据
  6. */
  7. @Controller
  8. @RequestMapping("/json")
  9. public class JsonController {
  10.  
  11. /**
  12. * 返回JSON数据
  13. * @param request
  14. * @param response
  15. */
  16. @RequestMapping("/json.do")
  17. public void json(HttpServletRequest request, HttpServletResponse response){
  18. Map<String, Object> data = new HashMap<String, Object>();
  19.  
  20. data.put("date", new Date());
  21. data.put("email", "accountwcx@qq.com");
  22. data.put("age", 30);
  23. data.put("name", "csdn");
  24. data.put("array", new int[]{1,2,3,4});
  25.  
  26. ResponseJsonUtils.json(response, data);
  27. }
  28.  
  29. /**
  30. * 返回JSONP数据
  31. * @param callback JSONP的回调函数
  32. * @param request
  33. * @param response
  34. */
  35. @RequestMapping("/jsonp.do")
  36. public void json(String callback, HttpServletRequest request, HttpServletResponse response){
  37. Map<String, Object> data = new HashMap<String, Object>();
  38.  
  39. data.put("date", new Date());
  40. data.put("email", "accountwcx@qq.com");
  41. data.put("age", 30);
  42. data.put("name", "csdn");
  43. data.put("array", new int[]{1,2,3,4});
  44.  
  45. if(callback == null || callback.length() == 0){
  46. //假设client没有发送回调函数,则使用默认的回调函数
  47. ResponseJsonUtils.jsonp(response, data);
  48. }else{
  49. //使用client的回调函数
  50. ResponseJsonUtils.jsonp(response, callback, data);
  51. }
  52. }
  53. }

Java Web返回JSON的更多相关文章

  1. 在Spring MVC Controller的同一个方法中,根据App还是WEB返回JSON或者HTML视图。

    如有高见,欢迎交流! 最近在做一个web的项目,web版已经开发完毕,现在正在进行手机APP的开发,开发中遇到一个问题: 就是web版和app版都有登录功能,本想着是分别走不同的URL,实际开发的时候 ...

  2. java 封装返回json数据

    做的东西,一直是用easyui的,和后台的交互数据都是json格式的. 今天想要单独弄一个json数据返回给前台,其实是比较简单的问题,json接触不多,记录一下. 代码: public static ...

  3. java web 基础 json 和 javaBean转化

    github地址: https://github.com/liufeiSAP/JavaWebStudy 实体类: package com.study.demo.domain; import com.f ...

  4. java ajax返回 Json 的 几种方式

    原文:https://blog.csdn.net/qq_26289533/article/details/78749057 方式 1. : 自写代码转 Json 需要  HttpHttpServlet ...

  5. JAVA 接口返回JSON格式转换类

    使用了Lombok插件 Result.java package com.utils; import com.jetsum.business.common.constant.Constant; impo ...

  6. MVC返回JSON数据格式书写方式

    返回json数据格式,多个返回值加,隔开 [Route("api/users/web")] //如果不加这个路由请这样调用:/api/users/web?schoolname=十五 ...

  7. J2EE Web开发入门—通过action是以传统方式返回JSON数据

    关键字:maven.m2eclipse.JSON.Struts2.Log4j2.tomcat.jdk7.Config Browser Plugin Created by Bob 20131031 l ...

  8. ASP.NET WEB API 返回JSON 出现2个双引号问题

    前言          在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...

  9. Web API返回JSON数据

    对Web API新手来说,不要忽略了ApiController 在web API中,方法的返回值如果是实体的话实际上是自动返回JSON数据的例如: 他的返回值就是这样的: { "Conten ...

随机推荐

  1. 浅谈单页应用和多页应用——Vue.js向

    浅谈单页应用和多页应用--Vue.js向 多页面 多页面应用:每次页面跳转,后台都会返回一个新的HTML文档,就是多页面应用. 在以往传统开发的应用(网站)大多都是多页面应用,路由由后端来写. 页面跳 ...

  2. Codeforces 914 C Travelling Salesman and Special Numbers

    Discription The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pas ...

  3. [CF678F]Lena and Queries

    题意: 初始有一个空集合$n$个操作有三种操作,如下:$1\ a\ b$表示向集合中插入二元组$(a,b)$$2\ i$表示删除第$i$次操作时所插入的二元组$3\ q$表示询问当前集合的二元组中,$ ...

  4. 【块状链表】AutSky_JadeK的块状链表模板+总结(STL版)

    Part 1.块状链表.   定位 插入 删除 数组 O(1) O(n) O(n) 链表 O(n) O(1) O(1) 对于线性表的以上常见操作来说,数组和链表都无法有效地解决.但是,若我们将链表的每 ...

  5. [CF911B]Two Cakes

    题目大意: 有两种蛋糕,分别被切成了a块和b块,要把这些蛋糕分到n个盘子里. 要求每个盘子里只能有一种蛋糕,每一种蛋糕都被分.问最优情况下,盘子里至少能放几个蛋糕. 思路: 二分答案. 由于每个蛋糕都 ...

  6. [CF911A]Nearest Minimums

    题目大意: 给你一个数列,问数列中最小数的最近距离. 思路: 直接模拟即可. #include<cstdio> #include<cctype> #include<alg ...

  7. 10.2(java学习笔记)JDBC事务简述

    一.事务 事务是指作为一系列操作组成的一个整体,该整体只有两种状态,要么全部执行,要么全部不执行. 当组成这个事务的所有语句都执行成功则该事务执行,只要有一条语句执行失败则该事务不执行. 假设这里有一 ...

  8. 使用gettext提取c#中的多语言占位符(nopCommerce示例篇)

    i18n国际化通常的作法是使用gettext,即在源码中使用特殊的关键字来标识这个字符串将可能被翻译,如 @if (Model.IsCustomerForumModerator) { <li c ...

  9. 简单说说DNS劫持_firefox吧_百度贴吧

    简单说说DNS劫持_firefox吧_百度贴吧 DNSSEC

  10. UML及其StarUML介绍

    http://blog.csdn.net/monkey_d_meng/article/details/6005764 http://www.uml.org.cn/oobject/200901203.a ...