今天稍微学习了一下Json,JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构:
“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object) ,纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。
值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。
这些都是常见的数据结构。事实上大部分现代计算机语言都以某种形式支持它们。这使得一种数据格式在同样基于这些结构的编程语言之间交换成为可能。
JSON具有以下这些形式:
对象是一个无序的“‘名称/值'对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值' 对”之间使用“,”(逗号)分隔。
好了还是不说废话了直接上例子吧!!这个小demo的设计是这样的,index.jsp页面访问服务器端的servlet,servlet向index.jsp传递数据,传递的数据时Json格式的,呵呵...废话,如果不是Json格式的数据我写这篇博客就相当于蒙骗观众了!
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。这里设计这两个类主要是更好的体现Json传递数据的方式和传递的数据格式
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数据了,也是这一个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) { 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); }); } }); });
再贴一个运行效果吧!!
网友评论文明上网理性发言已有0人参与
发表评论: