日期:2014-05-16 浏览次数:20404 次
package test.gson; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; public class TestGson extends ActionSupport { private static final long serialVersionUID = 1L; private Users user; public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } @Override public String execute() throws Exception { user = new Users(); user.setId(10000); user.setUserName("zhangsan"); user.setPwd("000000"); user.setEmail("zhangsan@sina.com"); Gson g = new Gson(); String json = g.toJson(user); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("application/json;charset=utf-8"); response.setHeader("Cache-Control","no-cache"); PrintWriter pw = response.getWriter(); pw.print(json); pw.flush(); pw.close(); return null; } }
<?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="jsons" extends="struts-default" namespace="/"> <action name="testGson" class="test.gson.TestGson"></action> </package> </struts>