struts2 gson

1.gson是json的开发包 参考http://code.google.com/p/google-gson/
下载导入gson-1.4.jar到lib目录下
编写action javabean类
GetGsonAction.java
package com.test.action.gson;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class GetGsonAction extends ActionSupport
{
	@Override
	public String execute() throws Exception
	{
		List<People> list = new ArrayList<People>();
		
		// Info of first user
		People people1 = new People();

		Address address1 = new Address();
		address1.setHomeAddress("beijing");
		address1.setCompanyAddress("shanghai");
		
		people1.setId(1);
		people1.setName("zhangsan");
		people1.setAddress(address1);
		
		People people11 = new People();
		people11.setId(5);
		people11.setName("zhangsan's friend1");
		
		People people12 = new People();
		people12.setId(6);
		people12.setName("zhangsan's friend2");
		
		List<People> list1 = new ArrayList<People>();
		list1.add(people11);
		list1.add(people12);
		
		people1.setFriends(list1);
		
		//Info of second user
		People people2 = new People();
		
		Address address2 = new Address();
		address2.setHomeAddress("liaoning");
		address2.setCompanyAddress("fujian");
		
		people2.setId(2);
		people2.setName("lisi");
		people2.setAddress(address2);
		
		People people21 = new People();
		people21.setId(10);
		people21.setName("lisi's friend1");
		
		People people22 = new People();
		people22.setId(11);
		people22.setName("lisi's friend2");
		
		List<People> list2 = new ArrayList<People>();
		list2.add(people21);
		list2.add(people22);
		
		people2.setFriends(list2);
		
		// put all the users into result list
		list.add(people1);
		list.add(people2);
		
		//获取Gson实例对象
		Gson gson = new Gson();
		
		//将listjava对象装化为JSON对象
		String result = gson.toJson(list);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json; charset=utf-8"); //输出文本为application
		response.setHeader("Cache-Control", "no-cache"); //取消浏览器缓存
		
		//获取输出流
		PrintWriter out = response.getWriter();
		//将JSON对象输出到客户端
		out.print(result);
		
		out.flush();
		out.close();
		
		return null;
	}
}


People.java
package com.test.action.gson;

import java.util.List;

public class People {
	private int id;
	private String name;
	private Address address;
	private List<People> friends;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public List<People> getFriends() {
		return friends;
	}

	public void setFriends(List<People> friends) {
		this.friends = friends;
	}

}


Address.java
package com.test.action.gson;

public class Address {
	private String homeAddress;
	private String companyAddress;

	public String getHomeAddress() {
		return homeAddress;
	}

	public void setHomeAddress(String homeAddress) {
		this.homeAddress = homeAddress;
	}

	public String getCompanyAddress() {
		return companyAddress;
	}

	public void setCompanyAddress(String companyAddress) {
		this.companyAddress = companyAddress;
	}
}

2.简单的 struts.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
	<package name="struts2.1" extends="json-default">		
	<!--	<action name="getXmlAction" class="com.test.action.xml.GetXmlAction"></action>
		<action name="getJsonAction" class="com.test.action.json.GetJsonAction">
			<result name="success" type="json">
			     <!--不包含序列化的属性-->
				<param name="excludeProperties">myAge</param>
				<!--父类序列化的属性-->
				<param name="ignoreHierarchy">false</param>
				<!--不包含空值属性-->
				<param name="excludeNullProperties">true</param>
				<!-- 
				<param name="root">person</param>
				-->
			</result>
		</action>-->		
		<action name="getGsonAction" class="com.test.action.gson.GetGsonAction"></action>	
	</package>
</struts>

3.客户端gson.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <script type="text/javascript" src="jQuery/jquery-1.4.2.js"></script>
    
    <script type="text/javascript">

    function getInfo()
    {
		$.post("getJsonAction.action",
		{
			name: $("#name").val()
		}, function(returnedData, status)
		{
			if("success" == status)
			{
				
			}
		}
		);
    }

    function getAllInfo()
    {
    	$.post("getGsonAction.action",
		{
			
		}, function(returnedData, status)
		{
			if("success" == status)
			{
				//returnedData = eval("(" + returnedData + ")");
				
				//alert(returnedData[0].address.homeAddress + "," + returnedData[0].friends[1].name);
                //普通字符串
				//var obj = "{name: 'zhangsan'}";
                //转化为json对象
				//var jsonObj = eval("(" + obj + ")");

				//alert(jsonObj.name);

				
				//var obj2 = {name : 'zhangsan'};

				//alert(obj2.name);

                //动态表格的构建
				var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>homeAddress</th><th>companyAddress</th></tr>";

				for(var i = 0; i < returnedData.length; ++i)
				{
					var person = returnedData[i];

					var id = person.id;
					var name = person.name;
					var homeAddress = person.address.homeAddress;
					var companyAddress = person.address.companyAddress;

					var tr = "<tr align='center'><td>" + id + "</td><td>" + name + "</td><td>"+ homeAddress + "</td><td>" + companyAddress + "</td></tr>";

					html += tr;
				}
				
				html += "</table>";

				$("body table:eq(0)").remove();
				$("#theBody").append(html);
			}	
		}
		);
    }
    
    </script>
    
  </head>
  
  <body id="theBody">
   
   <select id="name">
   		<option value="zhangsan" selected="selected">zhangsan</option>
   		<option value="lisi">lisi</option>
   </select>
   
   <input type="button" value="get info" onclick="getInfo();"> &nbsp;&nbsp;
   <input type="button" value="get all info" onclick="getAllInfo()">
   
   
  </body>
</html>


你可能感兴趣的:(java,apache,json,struts,Google)