JSON对象:
1.JSON(JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。JSON是JavaScript原生格式,这意味着在JavaScript中处理JSON数据不需要任何特殊的API或工具包。2.JSON的规则很简单:对象是一个无序的“‘名称:值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’对”之间使用“,”(逗号)分隔。
规则如下:
(1)映射用冒号(“:”)表示。名称:值
(2)并列的数据之间用逗号(“,”)分隔。名称1:值1,名称2:值2
(3) 映射的集合(对象)用大括号(“{}”)表示。{名称1:值1,名称2:值2}
(4) 并列数据的集合(数组)用方括号(“[]”)表示。
[
{名称1:值,名称2:值2},
{名称1:值,名称2:值2}
]
(5) 元素值可具有的类型:string, number, object, array, true, false, null
例一:
var people = {userName:"xxx",passWord:"111"};
alert(people.passWord);//获得111
例二:
var people = [{userName:"xxx1",passWord:"111"},{userName:"xxx2",passWord:"222"}]
alert(people[1].passWord);//获得222
例三:值test对应的value是一个数组
var people = {test:[{userName:"xxx1",passWord:"111"},{userName:"xxx2",passWord:"222"}]};
alert(people.test[0].passWord);//获得111
var people = [
{test1:[{userName:"xxx11",passWord:"11"},{userName:"xxx12",passWord:"12"}]},
{test2:[{userName:"xxx21",passWord:"21"},{userName:"xxx22",passWord:"22"}]},
{test3:[{userName:"xxx31",passWord:"31"},{userName:"xxx32",passWord:"32"}]}
];
alert(people[2].test3[0].passWord);//获得31
例五:
var people={
"userName":"xxx",
"age":"10",
"info":{"texl":"123456","telphone":"1333333"},
"address":[
{"city":"beijing","code":"1002"},
{"city":"huoxing","code":"2002"}
]
};
alert(people.address[1].city);//获得huoxing
例六:利用第三方组件在服务器端生成JSON数据后,传递给客户端,并解析
需要被生成json数据的javaBean
package com.xxc.test;
public class People {
private String userName;
private int age;
public People(String userName, int age) {
this.userName = userName;
this.age = 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;
}
}
package com.xxc.test;
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 net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
public class JsonServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
People p1 = new People("xxc1",10);
People p2 = new People("xxc2",20);
People p3 = new People("xxc3",30);
List<People> list = new ArrayList<People>();
list.add(p1);
list.add(p2);
list.add(p3);
//指定javaBean中的某个或某几个属性不进行json的数据生成
JsonConfig config = new JsonConfig();
config.setExcludes(new String[]{"age"});
JSONArray jsonarray = JSONArray.fromObject(list,config);
/*
* 如果没有config限制条件
* jsonarray.toString()--->[{"age":10,"userName":"xx1"},{"age":20,"userName":"xx2"},{"age":30,"userName":"xx3"}]
* 如果有age限制条件
* jsonarray.toString()--->[{"userName":"xxc1"},{"userName":"xxc2"},{"userName":"xxc3"}]
*/
System.out.println(jsonarray.toString());
out.println(jsonarray.toString());
//JSONObject object = JSONObject.fromObject(p1, config);这个是单独对一个对象进行json数据的生成
}
}
AJAX
<%@ 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 'json.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">
-->
<script type="text/javascript">
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
function test(){
var xmlhttprequest = ajaxFunction();
xmlhttprequest.onreadystatechange = function(){
if(xmlhttprequest.readyState == 4){
if(xmlhttprequest.status == 200 || xmlhttprequest.status ==304){
var result = xmlhttprequest.responseText;
alert(result);//没经过eval()方法处理的时候只是一段普通字符串
result = eval("("+result+")");//处理之后就成了json对象
alert(result[2].userName);
}
}
}
xmlhttprequest.open("post","servlet/JsonServlet?timestamp="+new Date().getTime(),true);
xmlhttprequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttprequest.send(null);
}
</script>
</head>
<body>
<input type="button" οnclick="test()" value="test">
</body>
</html>