在web工程中很多时候都会用到ajax技术,一般都会从服务器将数据转换为json字符串返回到页面。

这次使用的是阿里的fastjson第三方包 fastjson-1.2.8.jar

 

前台使用jquery的$.post来发送post请求

后台使用fastjson的第三方jar包

 * String s = JSON.toJSONString(集合)
 * String s = JSON.toJSONString(对象)
        
 * 如果List集合中存入相同引用的对象
      * fastjson默认的情况下是进行循环检测的,去除掉死循环调用的方式
      * 可以使用JSON.toJSONString(p,SerializerFeature.DisableCircularReferenceDetect) 去除循环检测,但是就会出现死循环的效果
      * 最后可以使用注解:@JSONField(serialize=false)对指定的属性不转换成json

//发送ajax请求获得级别
var url = \"${pageContext.request.contextPath}/ajaxDemo.action\";

$.post(
    url,
    //params,//可选参数格式为json格式{key:value}
    function(data){
       //处理返回的数据
        console.log(data);
    },
    \"json\"
);

 

action页面

    public String ajaxDemo() {
		
        User user = new User(\"alex\", 22);
        //获得response并将内容转为json字符串写回到页面
	HttpServletResponse response = ServletActionContext.getResponse();
        //SerializerFeature.DisableCircularReferenceDetect是关闭循环引用检测,不然有些引用的值在页面上是获取不到的。
	String jsonString = JSON.toJSONString(user,SerializerFeature.DisableCircularReferenceDetect);
        //设置返回字符的格式为json,编码为UTF-8
        response.setContentType(\"application/json;utf-8\");
	response.setCharacterEncoding(\"UTF-8\");
	try {
		response.getWriter().print(jsonString);
	} catch (IOException e) {
		e.printStackTrace();
	}	
		
	return NONE;
		
    }

fastjson工具类

package utils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class FastJsonUtil {
	
	/**
	 * 将对象转成json串
	 * @param  
	 * @return
	 */
	public static String toJSONString(   ){
		//DisableCircularReferenceDetect来禁止循环引用检测
		return JSON.toJSONString( ,SerializerFeature.DisableCircularReferenceDetect);
	}
	//输出json
	public static void write_json(HttpServletResponse response,String jsonString)
	{
		response.setContentType(\"application/json;utf-8\");
		response.setCharacterEncoding(\"UTF-8\");
		try {
			response.getWriter().print(jsonString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	/**
	 * ajax提交后回调的json字符串
	 * @return
	 */
	public static String ajaxResult(boolean success,String message)
	{
		Map map=new HashMap();
		map.put(\"success\", success);//是否成功
		map.put(\"message\", message);//文本消息
		String json= JSON.toJSONString(map);		
		return json;
	}
	

	/**
	 * JSON串自动加前缀
	 * @param json 原json字符串
	 * @param prefix 前缀
	 * @return 加前缀后的字符串
	 */

	public static String JsonFormatterAddPrefix(String json,String prefix,Map<String, > newmap)
	{
		if(newmap == null){
			newmap = new HashMap();
		}
		Map<String, > map = (Map) JSON.parse(json);

		for(String key:map.keySet())
		{
			   =map.get(key);
			if(isEntity( )){
				String jsonString = JSON.toJSONString( );
				JsonFormatterAddPrefix(jsonString,prefix+key+\".\",newmap);
				
			}else{
				newmap.put(prefix+key,  );
			}
			
		}
		return JSON.toJSONString(newmap);		
	}
	/**
	 * 判断某对象是不是实体
	 * @param  
	 * @return
	 */
	private static boolean isEntity(   )
	{
		if(  instanceof String  )
		{
			return false;
		}
		if(  instanceof Integer  )
		{
			return false;
		}
		if(  instanceof Long  )
		{
			return false;
		}
		if(  instanceof java.math.BigDecimal  )
		{
			return false;
		}
		if(  instanceof Date  )
		{
			return false;
		}
		if(  instanceof java.util.Collection )
		{
			return false;
		}
		return true;
		
	}
}


          

 

收藏 打印