先热热身!看看简单的json,格式吧:
package acc.testJSON; import org.json.JSONArray; import org.json.JSONObject; public class Test { /** * json格式说明 * {}一个对象 * []一个数组 * key:value * JSONArray * @param args */ public static void main(String[] args) { String json="{'user':'json','pass':'123'}"; //解悉json格式字符串 JSONObject jsonObj=new JSONObject(json); String user=jsonObj.getString("user"); String pass=jsonObj.getString("pass"); System.out.println("user: "+user+" \tpass: "+pass); System.out.println("------------------------------>"); //解析json数组格式 String jsonArray="[{'age':50, 'isOad':false, 'user':{'name':'胡锦涛', 'leve':100}},{'user':{'name':'习近平', 'leve':100}, 'age':333, 'isOad':true}]"; JSONArray array=new JSONArray(jsonArray); for(int i=0;i<array.length();i++){ //获取第i个数组内容,得到一个josn对象 JSONObject obj=array.getJSONObject(i); //输出josn对象的内容 System.out.println("age: "+obj.getInt("age")); System.out.println("isOad: "+obj.getBoolean("isOad")); //获取josn对象里的 用户对象 JSONObject userJ=obj.getJSONObject("user"); //输出用户对象 System.out.println("name: "+userJ.getString("name")+"\tleve: "+userJ.getInt("leve")); } } }
开始上主题!--------------------------------------------------
strtsu.xml 代码:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <include file="jqueryAction.xml" /> <package name="default1" namespace="/" extends="json-default"> <!-- xml对象方式 --> <action name="getXmlInfo" class="accp.struts2.GetXmlInfo"/> <!-- json --> <action name="getJsonInfo" class="accp.struts.json.GetJsonInfo"> <result name="success" type="json"> <!-- 排除属性,不会序列化 --> <param name="excludeProperties">myAge</param> <!-- 指定序列化从那个根开始 <param name="root">person</param> --> <!-- 序列化包括父类的属性 --> <param name="ignoreHierarchy">false</param> <!-- 排除空值的属性 --> <param name="excludeNullProperties">true</param> </result> </action> <!-- Gson Test --> <action name="gsonAction" class="accp.struts.json.GetGsonAction"> </action> </package> </struts>
xml 现在一般不用这 个,太麻烦,流量重
效果
xml jsp页面代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'xmlTest.jsp' starting page</title> <script type="text/javascript" src="jquery/jquery-1.9.1.js"> </script> <script type="text/javascript"> /** *ajax 第一个参数uri地址 *第二个参数:传送过去的值 *第三个参数:反回的回调函数(数据,状态); */ function getInfo(){ alert($("#name").val()); $.post( "getXmlInfo.action", { name:$("#name").val()}, function(returnedDatas,status){ if("success"==status) { var id=$(returnedDatas).find("id").text(); var name=$(returnedDatas).find("name").text(); var age=$(returnedDatas).find("age").text(); var adderss=$(returnedDatas).find("adderss").text(); var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>age</th><th>adderss</th></tr><tr>" +"<td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+adderss+"</td></tr></table>"; $("body table:eq(0)").remove(); $("#theBody").append(htmls); // alert(htmls); } } ); } </script> </head> <body id="theBody"> <select id="name"> <option>刘备</option> <option>张三</option> </select> <input type="button" value="获取信息" onclick="getInfo()"/> </body> </html>
package accp.struts2; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.dom4j.DocumentHelper; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import com.opensymphony.xwork2.ActionSupport; public class GetXmlInfo extends ActionSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String execute() throws Exception { Person person=new Person(); person.setId(1); person.setName("张三s"); person.setAge(20); person.setAdderss("dddddd"); Person person2=new Person(); person2.setId(2); person2.setName("刘备s"); person2.setAge(50); person2.setAdderss("aaaaa"); //构造一个xml Document docment=DocumentHelper.createDocument(); docment.setName("myXml"); //代表根元素 Element root=docment.addElement("users"); root.addComment("is a comment"); Element userElement= root.addElement("user"); Element id=userElement.addElement("id"); Element name=userElement.addElement("name"); Element age=userElement.addElement("age"); Element adderss=userElement.addElement("adderss"); if("刘备".equals(this.name)){ id.setText(person2.getId()+""); name.setText(person2.getName()); age.setText(person2.getAge()+""); adderss.setText(person2.getAdderss()); } if("张三".equals(this.name)){ System.out.println("进来了:"+this.name); id.setText(person.getId()+""); name.setText(person.getName()); age.setText(person.getAge()+""); adderss.setText(person.getAdderss()); } HttpServletResponse response=ServletActionContext.getResponse(); //response.setContentType("text/html; charset=utf-8"); response.setContentType("text/xml; charset=utf-8"); //去除缓存 response.setHeader("Cache-Control","no-cache"); PrintWriter out=response.getWriter(); OutputFormat format=OutputFormat.createPrettyPrint(); format.setEncoding("utf-8"); //把xml文件写入到out对象中 格式为format XMLWriter write=new XMLWriter(out,format); write.write(docment); //out.print(this.name); System.out.println("GetXmlInf:"+docment+"\nname:"+this.name); out.flush(); out.close(); return null; } }
json 效果图:
json jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'xmlTest.jsp' starting page</title> <script type="text/javascript" src="jquery/jquery-1.9.1.js"> </script> <script type="text/javascript"> function getInfo() { alert($("#name").val()); $.post("getJsonInfo.action", { name:$("#name").val()}, function(returnedDatas,status){ if("success"==status) { var name=returnedDatas.name; var adderss=returnedDatas.myAdderss; var age=returnedDatas.age; var id=returnedDatas.id; var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>age</th><th>adderss</th></tr><tr>" +"<td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+adderss+"</td></tr></table>"; $("body table:eq(0)").remove(); $("#theBody").append(htmls); // alert(name+"/"+adderss); //alert(returnedDatas); } } ); } </script> </head> <body id="theBody"> <select id="name"> <option>刘备</option> <option>张三</option> </select> <input type="button" value="获取信息" onclick="getInfo()"/> </body> </html>
package accp.struts.json; import java.util.Date; import org.apache.struts2.json.annotations.JSON; import com.opensymphony.xwork2.ActionSupport; public class GetJsonInfo extends ActionSupport { private String name; private int id; private int age; private String adderss; private Date date; private Person person=new Person(); public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } @JSON(format="yyyy-MM-dd",name="myDate",serialize=false) public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } @JSON(serialize=false)//禁止获取这个字段 public int getId() { return id; } public void setId(int id) { this.id = id; } //@JSON(name="myAge")//别名 在解悉的时候 要获取这个属性的名字 public int getAge() { return age; } public void setAge(int age) { this.age = age; } @JSON(name="myAdderss")//别名 在解悉的时候 要获取这个属性的名字 public String getAdderss() { return adderss; } public void setAdderss(String adderss) { this.adderss = adderss; } public String execute() throws Exception { Person person=new Person(); person.setId(1); person.setName("张三s"); person.setAge(20); person.setAdderss("dddddd"); person.setDate(new Date()); Person person2=new Person(); person2.setId(2); person2.setName("刘备s"); person2.setAge(50); person2.setAdderss("aaaaa"); person2.setDate(new Date()); if("张三".equals(this.name)){ this.id=person.getId(); this.age=person.getAge(); //this.name=person.getName(); this.adderss=person.getAdderss(); this.date=person.getDate(); } if("刘备".equals(this.name)){ this.id=person2.getId(); this.age=person2.getAge(); //this.name=person2.getName(); this.adderss=person2.getAdderss(); this.date=person2.getDate(); } System.out.println("OK完毕!"+this.name); return SUCCESS; } }
gosn jsp页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'gsonTest.jsp' starting page</title> <script type="text/javascript" src="jquery/jquery-1.9.1.js"> </script> <script type="text/javascript"> function getInfo() { $.post( "gsonAction.action", {name:$("#name").val()}, function(returnedDatas,status) { if("success"==status) { //var obj="{name:'zhangsan',n:'lishi'}"; //json对象需转换才能读取 //将returndates转换为Gson对象 //var JsonObj=eval("("+obj+")"); //alert(JsonObj.name+JsonObj.n); //var objs={age:"age:20"} // alert(objs.age); //var objAction=eval("("+returnedDatas+")"); //alert(objAction[0].name); alert("姓名:"+returnedDatas[0].name+",家园地址:"+returnedDatas[0].adderss.homeAdders); var htmls="<table width='980px' border='1' align='center'><tr> <td>id</td><th>name</th><th>公司地址</th><th>家庭adderss</th><th>朋友</th></tr>"; for(var i=0;i<returnedDatas.length;i++){ var JsonNode=returnedDatas[i]; htmls+="<tr><td>"+JsonNode.id+"</td><td>"+JsonNode.name +"</td><td>"+JsonNode.adderss.comanyAdders +"</td><td>"+JsonNode.adderss.homeAdders+"</td><td>" +JsonNode.list[0].name+",\t"+JsonNode.list[1].name+"</td></tr>"; } htmls+="</table>"; $("body table:eq(0)").remove(); $("#theBody").append(htmls); } } ); } </script> </head> <body id="theBody"> <select id="name"> <option>吴用</option> <option>宋江</option> </select> <input type="button" value="获取all信息" onclick="getInfo()"/> </body> </html>
package accp.struts.json; 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 { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String execute() throws Exception { /*------------------构造朋友对象---------------------------------*/ //朋友1 PeoPle people11=new PeoPle(); people11.setId(2); people11.setName("林冲"); Adderss adderss11=new Adderss(); adderss11.setHomeAdders("梁山坡冲11"); adderss11.setComanyAdders("朝廷冲11"); people11.setAdderss(adderss11); //朋友2 PeoPle people12=new PeoPle(); people12.setId(3); people12.setName("武松"); Adderss adderss12=new Adderss(); adderss12.setHomeAdders("梁山坡松12"); adderss12.setComanyAdders("朝廷松12"); people12.setAdderss(adderss12); //朋友3 PeoPle people13=new PeoPle(); people13.setId(4); people13.setName("李逵"); Adderss adderss13=new Adderss(); adderss13.setHomeAdders("梁山坡 李逵8号"); adderss13.setComanyAdders("朝廷 99号"); people13.setAdderss(adderss13); /*---------------------------------------------------*/ /** * 信息列表 集合 */ List<PeoPle> listObj=new ArrayList<PeoPle>(); /** * 吴用的个人信息 */ if(this.name.equals("吴用")){ PeoPle people1=new PeoPle(); people1.setId(1); people1.setName("吴用"); //地址 Adderss adderss=new Adderss(); adderss.setHomeAdders("梁山坡"); adderss.setComanyAdders("朝廷"); people1.setAdderss(adderss); //朋友列表 集合构造 List<PeoPle> list=new ArrayList<PeoPle>(); list.add(people11); list.add(people12); //吴用添加 朋友列表 people1.setList(list); //个人信息列表加入 listObj.add(people1); //吴用 } /** * 宋江个人信息 */ if(this.name.equals("宋江")){ PeoPle people2=new PeoPle(); people2.setId(20); people2.setName("宋江"); //地址 Adderss adderss2=new Adderss(); adderss2.setHomeAdders("梁山坡江"); adderss2.setComanyAdders("朝廷江"); people2.setAdderss(adderss2); //朋友列表集合构建 List<PeoPle> list2=new ArrayList<PeoPle>(); list2.add(people11); list2.add(people13); //朋友列表加入 people2.setList(list2); //个人信息列表加入 listObj.add(people2); //宋江 } /* * 把信息转换为gson对象 */ Gson gson=new Gson(); String GsonResult=gson.toJson(listObj); //返回客户端 HttpServletResponse response=ServletActionContext.getResponse(); response.setHeader("Cache-Control", "no-cache");//去除缓存 response.setContentType("application/json;charset=utf-8"); //response.setContentType("text/plain;charset=utf-8");//纯文本 //response.setContentType("text/json;charset=utf-8"); PrintWriter out=response.getWriter(); out.write(GsonResult); //写入PrintWriter对象,反回客户端 out.flush(); out.close(); System.out.println("GsonResult:"+GsonResult); return null; } }
人类:
package accp.struts.json; import java.util.List; public class PeoPle { private int id; private String name; private Adderss adderss; private List<PeoPle> list; //朋友列表 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 Adderss getAdderss() { return adderss; } public void setAdderss(Adderss adderss) { this.adderss = adderss; } public List<PeoPle> getList() { return list; } public void setList(List<PeoPle> list) { this.list = list; } }
地址类:
package accp.struts.json; public class Adderss { private String homeAdders; private String comanyAdders; public String getHomeAdders() { return homeAdders; } public void setHomeAdders(String homeAdders) { this.homeAdders = homeAdders; } public String getComanyAdders() { return comanyAdders; } public void setComanyAdders(String comanyAdders) { this.comanyAdders = comanyAdders; } }