Java Web返回JSON
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);
}
}
}
Java Web返回JSON的更多相关文章
- 在Spring MVC Controller的同一个方法中,根据App还是WEB返回JSON或者HTML视图。
如有高见,欢迎交流! 最近在做一个web的项目,web版已经开发完毕,现在正在进行手机APP的开发,开发中遇到一个问题: 就是web版和app版都有登录功能,本想着是分别走不同的URL,实际开发的时候 ...
- java 封装返回json数据
做的东西,一直是用easyui的,和后台的交互数据都是json格式的. 今天想要单独弄一个json数据返回给前台,其实是比较简单的问题,json接触不多,记录一下. 代码: public static ...
- java web 基础 json 和 javaBean转化
github地址: https://github.com/liufeiSAP/JavaWebStudy 实体类: package com.study.demo.domain; import com.f ...
- java ajax返回 Json 的 几种方式
原文:https://blog.csdn.net/qq_26289533/article/details/78749057 方式 1. : 自写代码转 Json 需要 HttpHttpServlet ...
- JAVA 接口返回JSON格式转换类
使用了Lombok插件 Result.java package com.utils; import com.jetsum.business.common.constant.Constant; impo ...
- MVC返回JSON数据格式书写方式
返回json数据格式,多个返回值加,隔开 [Route("api/users/web")] //如果不加这个路由请这样调用:/api/users/web?schoolname=十五 ...
- J2EE Web开发入门—通过action是以传统方式返回JSON数据
关键字:maven.m2eclipse.JSON.Struts2.Log4j2.tomcat.jdk7.Config Browser Plugin Created by Bob 20131031 l ...
- ASP.NET WEB API 返回JSON 出现2个双引号问题
前言 在使用ASP.NET WEB API时,我想在某个方法返回JSON格式的数据,于是首先想到的就是手动构建JSON字符串,如:"{\"result\" ...
- Web API返回JSON数据
对Web API新手来说,不要忽略了ApiController 在web API中,方法的返回值如果是实体的话实际上是自动返回JSON数据的例如: 他的返回值就是这样的: { "Conten ...
随机推荐
- luogu P1186 玛丽卡
题目描述 麦克找了个新女朋友,玛丽卡对他非常恼火并伺机报复. 因为她和他们不住在同一个城市,因此她开始准备她的长途旅行. 在这个国家中每两个城市之间最多只有一条路相通,并且我们知道从一个城市到另一个城 ...
- 【矩阵乘法】图中长度为k的路径的计数
样例输入 4 2 0 1 1 0 0 0 1 0 0 0 0 1 1 0 0 0 样例输出 6 #include<cstdio> #include<vector> using ...
- iOS计算富文本(NSMutableAttributedString)高度
有时候开发中我们为了样式好看, 需要对文本设置富文本属性, 设置完后那么怎样计算其高度呢, 很简单, 方法如下: - (NSInteger)hideLabelLayoutHeight:(NSStrin ...
- 【教训】 form表单提交时,action url中参数无效
今天提交一个表单,内容参考如下: <form action="add.php?a=123&b=456"> <input type="hi ...
- Word调整表格大小
在Word文档中创建表格后,用户往往需要根据输入的内容调整表格的行高和列宽,有时也需要对整个表格的大小进行调整. 在选择的表格上右击,选择快捷菜单中的“自动调整”—“根据内容调整表格”命令,Word将 ...
- Linux 命令缩写部分解释
转:http://blog.chinaunix.net/uid-28408358-id-3890783.html bin = BINaries /dev = DEVices /etc = ETCe ...
- android加密解密完美教程
经常使用加密算法:DES.3DES.RC4.AES,RSA等; 对称加密:des,3des,aes 非对称加密:rsa 不可逆加密:md5 加密模式:ECB.CBC.CFB.OFB等; 填充模式:No ...
- ylbtech-LanguageSamples-Attibutes(特性)
ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-Attibutes(特性) 1.A,示例(Sample) 返回顶部 “特性”示例 本示例 ...
- Java计算两个日期相差的天数
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; impor ...
- jstack来分析。当linux出现cpu被java程序消耗过高时
我们使用jdk自带的jstack来分析.当linux出现cpu被java程序消耗过高时,以下过程说不定可以帮上你的忙: 1.top查找出哪个进程消耗的cpu高 21125 co_ad2 18 ...