今天稍微學(xué)習(xí)了一下Json,JSON (JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。 易于人閱讀和編寫。同時也易于機器解析和生成。 JSON采用完全獨立于語言的文本格式,但是也使用了類似于C語言家族的習(xí)慣(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 這些特性使JSON成為理想的數(shù)據(jù)交換語言。
JSON建構(gòu)于兩種結(jié)構(gòu):
“名稱/值”對的集合(A collection of name/value pairs)。不同的語言中,它被理解為對象(object) ,紀(jì)錄(record),結(jié)構(gòu)(struct),字典(dictionary),哈希表(hash table),有鍵列表(keyed list),或者關(guān)聯(lián)數(shù)組 (associative array)。
值的有序列表(An ordered list of values)。在大部分語言中,它被理解為數(shù)組(array)。
這些都是常見的數(shù)據(jù)結(jié)構(gòu)。事實上大部分現(xiàn)代計算機語言都以某種形式支持它們。這使得一種數(shù)據(jù)格式在同樣基于這些結(jié)構(gòu)的編程語言之間交換成為可能。
JSON具有以下這些形式:
對象是一個無序的“‘名稱/值'對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結(jié)束。每個“名稱”后跟一個“:”(冒號);“‘名稱/值' 對”之間使用“,”(逗號)分隔。
好了還是不說廢話了直接上例子吧?。∵@個小demo的設(shè)計是這樣的,index.jsp頁面訪問服務(wù)器端的servlet,servlet向index.jsp傳遞數(shù)據(jù),傳遞的數(shù)據(jù)時Json格式的,呵呵...廢話,如果不是Json格式的數(shù)據(jù)我寫這篇博客就相當(dāng)于蒙騙觀眾了!
index.jsp端的代碼(先易后難的順序):
代碼如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> --> <mce:script type="text/javascript" src="js/jquery-1.3.2.js" mce_src="js/jquery-1.3.2.js"></mce:script> <mce:script type="text/javascript" src="js/login.js" mce_src="js/login.js"></mce:script> </head> <body> <table> <tr id="head"> <td>lastname</td> <td>firstname</td> <td>address</td> </tr> <tr id="tr0"> <td id="td0"></td> <td id="td1"></td> <td id="td2"></td> </tr> <tr id="tr1"> <td id="td0"></td> <td id="td1"></td> <td id="td2"></td> </tr> <tr id="tr2"> <td id="td0"></td> <td id="td1"></td> <td id="td2"></td> </tr> </table> </body> </html>
然后是兩個bean程序:Person和Address。這里設(shè)計這兩個類主要是更好的體現(xiàn)Json傳遞數(shù)據(jù)的方式和傳遞的數(shù)據(jù)格式
代碼如下:
package com.wk; public class Person { private String firstName; private String lastName; private Address address; public Person() { super(); } public Person(String firstName, String lastName, Address address) { super(); this.firstName = firstName; this.lastName = lastName; this.address = address; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } package com.wk; public class Address { private int id; private String detail; public Address() { super(); } public Address(int id, String detail) { super(); this.id = id; this.detail = detail; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } }
servlet代碼:
代碼如下:
package com.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.wk.Address; import com.wk.Person; public class PersonServlet extends HttpServlet{ private static final long serialVersionUID = 1L; static StringBuffer bf; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); List<Person> persons = new ArrayList<Person>(); PrintWriter out = resp.getWriter();
Person person1 = new Person(); Address a1 = new Address(); a1.setId(1); a1.setDetail("河北省"); person1.setFirstName("瓜"); person1.setLastName("傻"); person1.setAddress(a1); persons.add(person1);
Person person2 = new Person(); Address a2 = new Address(); a2.setId(2); a2.setDetail("江西省"); person2.setFirstName("蛋"); person2.setLastName("笨"); person2.setAddress(a2); persons.add(person2);
Person person3 = new Person(); Address a3 = new Address(); a3.setId(1); a3.setDetail("湖南省"); person3.setFirstName("癡"); person3.setLastName("白"); person3.setAddress(a3); persons.add(person3);
bf = new StringBuffer();
/* 組裝成json格式的字符串 * {"person":[ * {"firstname":"", "lastNmae":"", "address": {"id":"", "detail":""}}, * ]} */ bf.append("{"person":["); for(Person person : 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("}},"); } //將最后一個逗號去掉 int length = bf.length(); String newStr = bf.substring(0, length-1); bf = new StringBuffer(); bf.append(newStr);
bf.append("]}"); out.println(bf); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); }
下面的代碼就是Jquery如何解析Json數(shù)據(jù)了,也是這一個demo的核心代碼了:
代碼如下:
$(document).ready(function() { $("table").css("border-color", "lightblue").css("border-style", "solid"); $("#head").css("background-color", "lightblue"); $.ajax({ // 后臺處理程序 url : "Json", // 數(shù)據(jù)發(fā)送方式 type : "post", // 接受數(shù)據(jù)格式 dataType : "json", timeout : 20000,// 設(shè)置請求超時時間(毫秒)。 // 請求成功后回調(diào)函數(shù)。 success : function(dataObj) { var member = 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); }); } }); });
再貼一個運行效果吧?。?/P>
更多信息請查看IT技術(shù)專欄