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 [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。则输出为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", "[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);
		}
	}
}
时间: 2024-08-05 19:29:39

Java Web返回JSON的相关文章

Java Web返回JSON工具类

Web项目中经常涉及到AJAX请求返回JSON和JSONP数据.JSON数据在服务器端和浏览器端传输,本质上就是传输字符串,不过这个字符串符合JSON语法格式.浏览器端会按照普通文本的格式接收JSON字符串,最终JSON字符串转成JSON对象通过JavaScript实现.目前部分浏览器(IE9以下浏览器没有提供)和常用的JS库都提供了JSON序列化和反序列化的方法,如jQuery的AJAX请求可以指定返回的数据格式,包括text.json.jsonp.xml.html等. Web服务器端只要把J

java web 使用json要加入的jar 文件

如果有类似错误可以参考,版本不同,记得看下里面包名是否和报错信息对应的上. commons-beanutils-1.8.0.jar不加这个包 java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean commons-collections.jar 不加这个包 java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedM

java web 基础 json 和 javaBean转化

github地址: https://github.com/liufeiSAP/JavaWebStudy 实体类: package com.study.demo.domain; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class Student { @JsonProperty(value="anothername") private String name; p

Web Api 中返回JSON的正确做法

小分享:我有几张阿里云优惠券,用券购买或者升级阿里云相应产品最多可以优惠五折!领券地址:https://promotion.aliyun.com/ntms/act/ambassador/sharetouser.html?userCode=ohmepe03 在使用Web Api的时候,有时候只想返回JSON:实现这一功能有多种方法,本文提供两种方式,一种传统的,一种作者认为是正确的方法. JSON in Web API – the formatter based approach 只支持JSON最

spring mvc返回json字符串数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable

1.spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable 2. @RequestMapping(value = { "/actor_details" }, method = { RequestMethod.POST }) @ResponseBody public ResultObject actorDetails(@RequestBody ActorDetailsRequest req)

MVC web api 返回JSON的几种方式,JSON时间去T的几种方式。

MVC web api 返回JSON的几种方式 1.在WebApiConfig的Register中加入以下代码 1 config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 2.在WebApiConfig的Register中加入以下代码 1 config.Formatters.Remove(config.Formatters.XmlFormatter);

快速掌握Ajax-Ajax基础实例(Ajax返回Json在Java中的实现)

(转)实例二:Ajax返回Json在Java中的实现 转自http://www.cnblogs.com/lsnproj/archive/2012/02/09/2341524.html#2995114 在这篇中主要是说一下使用Json来将后台取得的数据显示到前台页面.可以说这种方法应该是实现无刷新分页的基础,而且在开发过程中经常被用到.这里的后台部分由JAVA来实现. 这个例子也在上一篇中那个项目中实现.新建一个SecondTest.html页面,定义一个按钮,并给这个按钮绑定事件ajaxJson

Web Api 中返回JSON的正确做法(转)

出处:http://www.cnblogs.com/acles/archive/2013/06/21/3147667.html 在使用Web Api的时候,有时候只想返回JSON:实现这一功能有多种方法,本文提供两种方式,一种传统的,一种作者认为是正确的方法. JSON in Web API – the formatter based approach 只支持JSON最普遍的做法是:首先清除其他所有的formatters,然后只保留JsonMediaTypeFormatter. 有了HttpCo

web Api 返回json 的两种方式

web api写api接口时默认返回的是把你的对象序列化后以XML形式返回,那么怎样才能让其返回为json呢,下面就介绍两种方法: 方法一:(改配置法) 找到Global.asax文件,在Application_Start()方法中添加一句: . 代码如下: GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 修改后: . 代码如下: protected void Appli