json对象的传输函數的定義

/**
* List转换json格式向前端传递json数据流
* @param list
* @param response
* @throws IOException
*/
public void writeJson(List list,HttpServletResponse response) throws IOException{
JSONArray jarray=JSONArray.fromObject(list);
response.setHeader("Content-type", "text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jarray.toString());
}
/**
*
* 将一个字段以{key,value}转为json格式字符串返回ajax回调函数
* @param key
* @param object
* @param response
* @throws IOException
*/
public void toJson(String key,Object object, HttpServletResponse response) throws IOException{
JSONObject obj=new JSONObject();
obj.put(key, object);
response.setHeader("Content-type", "text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj.toString());
}

/**
*
* 普通类型的bean转换成json格式字符串返回ajax回调函数
* @param object
* @param response
* @throws IOException
*/
public void toJson(Object object, HttpServletResponse response) throws IOException{
JSONObject obj=JSONObject.fromObject(object);
response.setHeader("Content-type", "text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj.toString());
}

////////////////////////////////////////
用法(调用函数,把对象放入函数中): writeJson(items, response);

原文地址:https://www.cnblogs.com/OP-RONG/p/4193344.html