JSON(JavaScriptObject Notation)是一种轻量级的数据交换格式。简单地说,JSON可以将JavaScript对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从Web客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是JavaScript很容易解释它,而且JSON可以表示比"名称/值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。
下面举几个简单的实例来介绍Json,因为JSON是javascript的原生格式,因此不需要任何特殊的API包或工具包。
实例一:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function testJson(){
var user =
{
"name":"tom",
"age":11,
"info":{"tel":"lf","cellphone":"1223"},
"address":
[
{"city":"lf","postcode":"111"},
{"city":"bj","postcode":"222"},
]
}
alert(user.name);
alert(user.info.cellphone);
alert(user.address[1].postcode);
}
</script>
</head>
<body>
<input type="button" value="TestJson" οnclick="testJson()">
</body>
</html>
可直接运行测试。
实例二:
下面这个实例是前后台如何交互的实例,首先把环境搭起来,创建一个Maven项目json_test,具体创建过程不再赘余,pom.xml文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tgb</groupId>
<artifactId>json_test</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>json_test Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>json_test</finalName>
</build>
</project>
Web.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>json_test</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMVC的配置文件和web.xml文件在同一个目录下,springMVC-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.tgb.json" />
<mvc:annotation-driven />
<mvc:resources location="/js/" mapping="/js/**"/>
</beans>
上面关于SpringMVC的东西也不多讲,因为这不是要讲的重点。项目中还会用到Jquery,因此大家自行下载jquery包,放到webapp/js包下。
下面开始编写后台的代码,首先创建一个POJO类User:
package com.tgb.json;
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
然后创建TestJson类,在这个类中,我写了三个方法,是分别测试传递User对象、List集合和Map的。
package com.tgb.json;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestJson {
@RequestMapping("logon.do")
public String logon(HttpServletRequest request,HttpServletResponse response){
return "/test/addUser";
}
//返回User对象
@RequestMapping("/test/json1")
public void returnUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
User u1 = new User();
u1.setUsername("tom1");
u1.setAge(11);
//Json返回实体
JSONObject jsonObject = JSONObject.fromObject(u1);
//返给ajax请求
out.print(jsonObject);
}
//返回List
@RequestMapping("/test/json2")
public void returnList(HttpServletRequest request,HttpServletResponse response) throws Exception{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//传递List
List<User> list = new ArrayList<User>();
User u1 = new User();
u1.setUsername("tom1");
u1.setAge(11);
User u2 = new User();
u2.setUsername("jack");
u2.setAge(22);
list.add(u1);
list.add(u2);
//Json返回list
JSONArray jsonArray = JSONArray.fromObject(list);
//返给ajax请求
out.print(jsonArray);
}
//返回Map
@RequestMapping("/test/json3")
public void returnMap(HttpServletRequest request,HttpServletResponse response) throws Exception{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Map<String,User> map = new HashMap<String,User>();
User u1 = new User();
u1.setUsername("tom1");
u1.setAge(11);
User u2 = new User();
u2.setUsername("jack");
u2.setAge(22);
map.put("u1", u1);
map.put("u2", u2);
//Json返回map
JSONObject jsonObject = JSONObject.fromObject(map);
//返给ajax请求
out.print(jsonObject);
}
}
完成了后台代码的编写,页面上就需要获取后台传过来的Json数据,并将它显示出来,创建页面testJson.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="json_test/../js/jquery-1.7.1.js"></script>
<title>Insert title here</title>
<script type="text/javascript">
//获取User对象
function getJsonObject(){
$.ajax({
type:"POST",
url:"/json_test/test/json1",
dataType:"json",
success:function(json){
alert(json.username);
alert(json.age);
},
error:function(){
alert("网络错误!");
}
});
}
//获取List对象
function getJsonList(){
$.ajax({
type:"POST",
url:"/json_test/test/json2",
dataType:"json",
success:function(json){
alert(json[0].username);
alert(json[1].age);
},
error:function(){
alert("网络错误!");
}
});
}
//获取Map对象
function getJsonMap(){
$.ajax({
type:"POST",
url:"/json_test/test/json3",
dataType:"json",
success:function(json){
alert(json.u1.username);
alert(json.u2.age);
},
error:function(){
alert("网络错误!");
}
});
}
</script>
</head>
<body>
<input type="button" value="获取User对象" οnclick="getJsonObject()"><br/>
<input type="button" value="获取List" οnclick="getJsonList()"><br/>
<input type="button" value="获取Map" οnclick="getJsonMap()">
</body>
</html>
通过以上这几个例子基本能说明Json的大致用途,他和XML的联系与区别,大家可自行查阅。