其實json的核心思想就是對象和字串在伺服器端和用戶端的相互轉化,通過json.jar和json.js來實現,可以使伺服器端接收上來的資料自動進行實體的轉換,也使得用戶端不用再因拼接字串而煩惱.
是比 xml 更好的資料格式 :
1) 能夠表示出 複雜的資料結構 .
2) 在用戶端 和 伺服器 端都能夠很方便的解析 .
-----------------------------------------------------------------------
JSON :
1, 定義了一種描述資料的格式 .
student( id , name , age , email ) ;
"{ 'id':'1' , 'name':'zhangsan' , 'age':10 ,
'email':'zhangsan@cernet.com' ,
'address' : { 'street':'xxxx' , 'postcode':'1111'
} ,
'phone' : ['1111' , '22222' , '33333']
}"
2, json.js 提供了兩個函數 .
javascript object <---> str
|-> stringify( object ) --> str
|-> parse( str ) --> obj
3, json.jar 在伺服器端的java代碼中 對json 字串進行轉化 .
XmlHttpRequest
|-> user{ id , name , age , email .} [javascript]
|-> json.js --> string( json format) .
string (json format)===> Server ( java object )
==> json.jar ( string --> java object )
{ "id":1,
"name":"zhangsan",
"age":20,
"email":[ "emailA","emailB","emailC"] ,
"address": { "street":"aaaaa","postcode":"1234"}
}
JSON.stringify( obj ) ===> str :
向伺服器發送資料之前調用 ,將要發送的資料儲存在對象中 obj---stringify --> str ===> server
JSON.parse( str ) --> Obj:
接受到伺服器的應答(str)之後, 調用parse將伺服器應答的字串轉化為對象,對其中的資料進行使用 。
Client:
button --> onclick --> reg()
|-> createUser
|-> JSON.stringify() -> string
|-> send( string ) ....
Serlvet:
readJsonString() : get string from request .
new JSONObject( str );
insert() : get data from JSONObject
respnose :
|-> ok
|-> error ;
reqCallBack()
|-> alert( ok ) ;
|-> alert( error ) ;
伺服器從用戶端接收資料的方式:
request.getInputStream()
==> InputStream [ ==> BufferedReader ]
==> is.read() | br.readLine() => xmlData
--------------------------------------------------------------------------------------------------------------
以下為範例程式碼:
==============================================================================================================
//這是在頁面上的對象字串間的轉化
<html>
<head>
<script type="text/javascript" src="./json.js"></script>
<script type="text/javascript">
function testStringify(){
var obj = new Object();
obj.id=1 ;
obj.name="zhangsan" ;
obj.age=20 ;
obj.email = [ "emailA" , "emailB" , "emailC" ] ;
obj.address= { street : "aaaaa" , postcode : "1234" } ;
var str = JSON.stringify( obj ) ;
document.write( "<h3>" + str + "</h3>" ) ;
}
function testParse(){
var str = '{ "orderItem": [ { "number":10 ,"product" : { "id":1, "name":"book" , "price":10} } , { "number":2 ,"product" : {"id":2 , "name":"USB" , "price": 100} } , { "number":3 , "product" :{ "id":3 , "name":"DVD" , "price" : 5 } } ]} ' ;
var order = JSON.parse( str ) ;
for( var i = 0 ; i < order.orderItem.length ; i++ ){
document.write( "<h3>number = " + order.orderItem[i].number + "</h3>" ) ;
document.write( "<h3> Product " + order.orderItem[i].product.id + " " +order.orderItem[i].product.name + " " + order.orderItem[i].product.price + "</h3>" ) ;
document.write( "<hr/>" ) ;
}
}
</script>
</head>
<body>
<input type="button" value="test stringify" onclick="testStringify();"/>
<input type="button" value="test parse" onclick="testParse()"/>
</body>
</html>
==============================================================================================================
//這是在Java中測試字串向對象轉化及對象轉成字串
package test.ajax.json ;
import org.json.* ;
public class TestJsonObject{
public static void main( String args[] ) throws Exception{
//已接收上來的串
String str = "{\"id\":1,\"name\":\"testjson\",\"age\":20,\"email\":[\"emailA\",\"emailB\",\"emailC\"],\"address\": {\"street\":\"aaaaa\",\"postcode\":\"1234\"}}" ;
//上面的/"是轉意字元,其實就如此串一樣,其根本原因就是區分:" {'id':1,'name':'testjson','age':20,'email':['emailA','emailB','emailC'],'address':{'street':'aaaaa','postcode':'1234'}}"
//進行字串向對象的轉化
JSONObject json = new JSONObject( str ) ;
//轉換後的輸出
System.out.println( "id = " + json.getInt( "id" ) ) ;
System.out.println( "name= " + json.getString( "name" ) ) ;
System.out.println( "age = " + json.getInt( "age" ) ) ;
//數組的接收
JSONArray array = json.getJSONArray( "email" ) ;
for( int i = 0 ; i < array.length() ; i++ ){
System.out.println( array.getString( i ) ) ;
}
//對象中的對象處理方式
JSONObject address = json.getJSONObject( "address" ) ;
System.out.println( "street " + address.getString( "street" ) ) ;
System.out.println( "postcode " + address.getString( "postcode" ) ) ;
//對象轉成字串
System.out.println( json.toString() ) ;
}
}
================================================================================================================
下面是前背景一個應用樣本:
RegServlet.java
*****************************************************************************************************************
package com.kettas.ajax ;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class RegServlet extends HttpServlet{
@Override
public void service( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
try{
String jsonStr = readJsonString( request ) ;
System.out.println( jsonStr ) ;
//返回成功應答
out.print( "ok" ) ;
out.flush();
}catch( Exception e ){
e.printStackTrace();
//返回失敗應答
out.print( "error" ) ;
out.flush() ;
}
}
private String readJsonString( HttpServletRequest request) throws Exception{
InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader( is ) ) ;
String str = "" ;
String temp = "" ;
while( true ){
temp = br.readLine();
if( temp == null ){
break ;
}
str += temp ;
}
return str ;
}
}
==========================================================================================================
register.html
*****************************************************************************************************************
<html>
<head>
<script type="text/javascript" src="./json.js"></script>
<script type="text/javascript">
var xhr ;
//初始化 xhr 對象
// return value : 1 : IE , 2 , Mozila , 0 : create xhr error ;
function createXHR(){
//1,建立xhr 對象 .
if( window.ActiveXObject ){
xhr = new ActiveXObject( "Microsoft.XMLHTTP" ) ;
return 1 ;
}else if( window.XMLHttpRequest ){
xhr = new XMLHttpRequest();
return 2 ;
}else{
return 0 ;
}
}
////////////////// 執行使用者註冊 //////////////////////
function reg(){
//1,建立並初始化User對象
var user = createUser();
//2, 將User對象轉化為要發送的字串( json 格式 )
var str = JSON.stringify( user ) ;
//3, 建立xhr對象
createXHR();
//4, 發送請求
xhr.onreadystatechange = regCallBack ;
sendRegRequest( str );
}
function createUser(){
var user = new Object();
user.name = document.getElementById( "nameId" ).value ;
user.password = document.getElementById( "passwordId" ).value ;
user.email = document.getElementById( "emailId" ).value ;
user.phone = document.getElementById( "phoneId" ).value ;
return user ;
}
function sendRegRequest( data ){
xhr.open( "post" , "/ajax/reg" ) ;
xhr.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" ) ;
xhr.send( data ) ;
}
function regCallBack(){
if( xhr.readyState == 4 ){
if( xhr.status == 200 ){
handleRegResult();
}else{
alert( "error , status=" + xhr.status ) ;
}
}
}
function handleRegResult(){
//alert( xhr.responseText ) ;
if( xhr.responseText == "ok" ){
alert( "reg ok" ) ;
}else if( xhr.responseText == "error" ){
alert( "system is busy,please try again later." ) ;
}else{
alert( "error!" ) ;
}
}
</script>
</head>
<body>
<h1>User Register</h1>
<table>
<tbody>
<tr>
<td >User Name</td>
<td><input type="text" id="nameId"/>
<span id="msgId"></span>
</td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="passwordId" /></td>
</tr>
<tr>
<td>email</td>
<td>
<input type="text" id="emailId"/>
</td>
</tr>
<tr>
<td>phone:</td>
<td><input type="text" id="phoneId"/></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="user register" onclick="reg()"/>
</td>
</tr>
</tbody>
</table>
</body>
</html>
==========================================================================================================
web.xml
*****************************************************************************************************************
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>regServlet</servlet-name>
<servlet-class>com.kettas.ajax.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>regServlet</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>