Ajax跨域调用后台Restful接口时的JSON转换方法

类:AjaxExchange
作用:将后台取到的数据以JSON或HTML的形式返回

package org.sun.com;

import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

public class AjaxExchange {
    
    // 转换成HTML形式返回,参数为String类型
    public static void printData(HttpServletResponse response, String msg) {  
        try {  
        	// 跨域配置
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "3600");	// 保持跨域Ajax时的Cookie
            response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token");

            response.setContentType("text/html;charset=utf-8");  
            response.setCharacterEncoding("UTF-8");  
            PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));  
            out.println(msg);  
            out.close();  
        } catch (Exception e) {    
            e.printStackTrace();  
        }  
   }  

    // 将任意类型的item转换成JSON并返回  
    public static void printDataJason(HttpServletResponse response, Object item) {  
        try {  
        	// 跨域配置
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "3600");	// 保持跨域Ajax时的Cookie
            response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token");

        	response.setContentType("text/json;charset=utf-8");  
        	response.setCharacterEncoding("UTF-8");  
        	PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));  
    		
        	// currentUser里面有循环导致json处理不了
    		JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
    		jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
    		jsonConfig.setExcludes(new String[]{"currentUser"});
    		
        	JSONArray jsonArr = JSONArray.fromObject(item, jsonConfig);
            out.println(jsonArr); 
  
            out.close();  
        } catch (Exception e) {    
        	e.printStackTrace();    
        }  
	}  

    // 带JsonConfig的JSON转换
    public static void printDataJason(HttpServletResponse response, Object item, JsonConfig jsonConfig) {  
        try {  
        	// 跨域配置
            response.setHeader("Access-Control-Allow-Origin","*");
            response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "3600");	// 保持跨域Ajax时的Cookie
            response.setHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with,Authorization,Origin, Accept, Content-Type,x-xsrf-token");

        	response.setContentType("text/json;charset=utf-8");  
        	response.setCharacterEncoding("UTF-8");  
        	PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));  
           
        	JSONArray jsonArr = JSONArray.fromObject(item, jsonConfig);
            out.println(jsonArr); 
  
            out.close();  
        } catch (Exception e) {    
        	e.printStackTrace();    
        }  
	}
}

这里第二个方法和第三个方法很像,区别在于第三个方法多了个JsonConfig的参数,这是用来设置Json转换时的一些参数的。

我在返回数据转Json的时候到这样的问题:
我想返回的参数是类型A,但是类型A继承了类型B,类型B里面有些数据是类型C,类型C里面有些类型是类型D
结果变成了这样A→B→C→D→...
JSONArray转换的时候,会根据这个顺序循环,把类型ABCD...里面的数据都JSON化。
如果A→B→C→D→C时,C和D产生循环的话,JSON就无法转换了。

        	// currentUser里面有循环导致json处理不了
    		JsonConfig jsonConfig = new JsonConfig();  //建立配置文件
    		jsonConfig.setIgnoreDefaultExcludes(false);  //设置默认忽略
    		jsonConfig.setExcludes(new String[]{"currentUser"});
我找到了发生类型循环出错的参数并在方法2中写死了。也可以在外面设置出错的参数并传到方法3中。

调用方法如下:
    @RequestMapping(value = "/restful/getQuestion")
    public void getQuestion(HttpServletRequest request, HttpServletResponse response) {

    	RestfulResult restfulResult = new RestfulResult();
    	
    	try{
                // 将数据取出放入restfulResult
	        ...
                restfulResult.setData(...);
    	}
	catch(Exception ex)
	{
	  	restfulResult.setResult("Error");
	    	restfulResult.setMessage(ex.getMessage());
	}

    	AjaxExchange.printDataJason(response, restfulResult);
    } 


追加:

也可以在Entity定义的时候,加上@jsonignore

json会在转换的时候自动忽略此字段


用到的Jar包可以去这里下载:
jsonArray转换需要用到的Jar包

你可能感兴趣的:(Java)