Jquery解析Json格式数据过程代码
今天稍微学习了一下Json,JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C,C++,C#,Java,JavaScript,Perl,Python等)。这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
“名称/值”对的集合(Acollectionofname/valuepairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hashtable),有键列表(keyedlist),或者关联数组(associativearray)。
值的有序列表(Anorderedlistofvalues)。在大部分语言中,它被理解为数组(array)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。
JSON具有以下这些形式:
对象是一个无序的“‘名称/值'对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值'对”之间使用“,”(逗号)分隔。
好了还是不说废话了直接上例子吧!!这个小demo的设计是这样的,index.jsp页面访问服务器端的servlet,servlet向index.jsp传递数据,传递的数据时Json格式的,呵呵...废话,如果不是Json格式的数据我写这篇博客就相当于蒙骗观众了!
index.jsp端的代码(先易后难的顺序):
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'index.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--<linkrel="stylesheet"type="text/css"href="styles.css"mce_href="styles.css">--><mce:scripttype="text/javascript"src="js/jquery-1.3.2.js"mce_src="js/jquery-1.3.2.js"></mce:script><mce:scripttype="text/javascript"src="js/login.js"mce_src="js/login.js"></mce:script></head><body><table><trid="head"><td>lastname</td><td>firstname</td><td>address</td></tr><trid="tr0"><tdid="td0"></td><tdid="td1"></td><tdid="td2"></td></tr><trid="tr1"><tdid="td0"></td><tdid="td1"></td><tdid="td2"></td></tr><trid="tr2"><tdid="td0"></td><tdid="td1"></td><tdid="td2"></td></tr></table></body></html>
然后是两个bean程序:Person和Address。这里设计这两个类主要是更好的体现Json传递数据的方式和传递的数据格式
packagecom.wk;publicclassPerson{privateStringfirstName;privateStringlastName;privateAddressaddress;publicPerson(){super();}publicPerson(StringfirstName,StringlastName,Addressaddress){super();this.firstName=firstName;this.lastName=lastName;this.address=address;}publicStringgetFirstName(){returnfirstName;}publicvoidsetFirstName(StringfirstName){this.firstName=firstName;}publicStringgetLastName(){returnlastName;}publicvoidsetLastName(StringlastName){this.lastName=lastName;}publicAddressgetAddress(){returnaddress;}publicvoidsetAddress(Addressaddress){this.address=address;}}packagecom.wk;publicclassAddress{privateintid;privateStringdetail;publicAddress(){super();}publicAddress(intid,Stringdetail){super();this.id=id;this.detail=detail;}publicintgetId(){returnid;}publicvoidsetId(intid){this.id=id;}publicStringgetDetail(){returndetail;}publicvoidsetDetail(Stringdetail){this.detail=detail;}}
servlet代码:
packagecom.servlet;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.wk.Address;importcom.wk.Person;publicclassPersonServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;staticStringBufferbf;@OverrideprotectedvoiddoGet(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{resp.setContentType("text/html;charset=utf-8");List<Person>persons=newArrayList<Person>();PrintWriterout=resp.getWriter(); Personperson1=newPerson();Addressa1=newAddress();a1.setId(1);a1.setDetail("河北省");person1.setFirstName("瓜");person1.setLastName("傻");person1.setAddress(a1);persons.add(person1); Personperson2=newPerson();Addressa2=newAddress();a2.setId(2);a2.setDetail("江西省");person2.setFirstName("蛋");person2.setLastName("笨");person2.setAddress(a2);persons.add(person2); Personperson3=newPerson();Addressa3=newAddress();a3.setId(1);a3.setDetail("湖南省");person3.setFirstName("痴");person3.setLastName("白");person3.setAddress(a3);persons.add(person3); bf=newStringBuffer(); /*组装成json格式的字符串*{"person":[*{"firstname":"","lastNmae":"","address":{"id":"","detail":""}},*]}*/bf.append("{\"person\":[");for(Personperson:persons){bf.append("{\"firstname\":\"").append(person.getFirstName()).append("\",\"").append("lastname\":\"").append(person.getLastName()).append("\",").append("\"address\":").append("{\"id\":\"").append(person.getAddress().getId()).append("\",\"").append("detail\":\"").append(person.getAddress().getDetail()).append("\"").append("}},");}//将最后一个逗号去掉intlength=bf.length();StringnewStr=bf.substring(0,length-1);bf=newStringBuffer();bf.append(newStr); bf.append("]}");out.println(bf);}@OverrideprotectedvoiddoPost(HttpServletRequestreq,HttpServletResponseresp)throwsServletException,IOException{this.doGet(req,resp);}
下面的代码就是Jquery如何解析Json数据了,也是这一个demo的核心代码了:
$(document).ready(function(){$("table").css("border-color","lightblue").css("border-style","solid");$("#head").css("background-color","lightblue");$.ajax({//后台处理程序url:"Json",//数据发送方式type:"post",//接受数据格式dataType:"json",timeout:20000,//设置请求超时时间(毫秒)。//请求成功后回调函数。success:function(dataObj){varmember=eval(dataObj);//alert(member.person[1].firstname);$(dataObj.person).each(function(i,per){$("#tr"+i).find("#td0").html(per.lastname);$("#tr"+i).find("#td1").html(per.firstname);$("#tr"+i).find("#td2").html(per.address.detail);});}});});
再贴一个运行效果吧!!