JSON

JSON

1.json是什麼

  * 它是js提供的一種數據交換格式!javascript

2.json的語法

  * { }:是對象!css

    > 屬性名必須使用雙引號括起來!單引號不行!!!html

    > 屬性值:java

      * nullajax

      * 數值json

      * 字符串數組

      * 數組:使用[ ]括起來瀏覽器

      * boolean值:true和false服務器

3.應用json

  * var person={"name":"金泰妍", "age":18, "sex":"female" };app

代碼示例:

AServlet:

package day23_3;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        /*
         * 向客戶端發送json字符串
         */
        String str="{\"name\":\"金泰妍\"}";
        System.out.println(str);
        response.getWriter().print(str);
    }
}

json2.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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>json2</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 createXMLHttpRequest() {
        try {
            return new XMLHttpRequest();
        } catch (e) {
            try {
                return new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("不曉得你用的什麼瀏覽器!");
                    throw e;
                }
            }
        }
    }
    
        window.onload=function(){
            var btn=document.getElementById("btn");
            btn.onclick=function(){
                //使用ajax獲得服務器端的響應,把結果顯示到h3中
                var xmlHttp = createXMLHttpRequest();
                xmlHttp.open("GET", "<c:url value='/AServlet'/>", true);
                xmlHttp.send(null);
                xmlHttp.onreadystatechange=function(){
                    if(xmlHttp.readyState==4&&xmlHttp.status==200){
                        var text=xmlHttp.responseText;//它是一個json串
                        //執行json串
                        var person=eval("("+text+")");//轉換成js對象
                        var s=person.name;//變成字符串
                        document.getElementById("h3").innerHTML=s;
                    }
                };
            };
        };
    </script>

  </head>
  
  <body>
       <button id="btn">點這裏</button>
    <h1>json</h1>
    <h3 id="h3"></h3>
  </body>
</html>

4.JSON與XML比較

  * 可讀性:XML勝出;

  * 解析難度:JSON自己就是JS對象,全部簡單不少;

  * 流行度: XML已經流行好多年,但在AJAX領域,JSON更受歡迎。


 

json-lib

1.是什麼?

  * 它能夠把JavaBean轉換成json字符串

2.jar包

json-lib的核心jar包有:

  json-lib.jar

json-lib的依賴jar包有:

  commons-lang.jar

  commons-beanutils.jar

  commons-logging.jar

  commons-collection.jar

  ezmorph.jar

3.核心類

  * JSONObject--->Map

    > toString();

    > JSONObject  map = JSONObject.fromObject(person):把對象轉換成JSONObject對象 

  * JSONArray--->List

    > tonString();

    > JSONArray jsonArray=JSONArray.fromObject(list):把list轉換成JSONArray對象

 代碼示例:

package com.xjs.demo1;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.junit.Test;

/**
 * 演示JSON-lib小工具
 * @author hp
 *
 */
public class Demo1 {
    @Test
    public void fun1(){
        JSONObject map=new JSONObject();
        map.put("name", "金泰妍"); 
        map.put("age", 18);
        map.put("sex", "female");
        
        String s=map.toString();
        System.out.println(s);
    }
    
    @Test
    public void fun2(){
        Person p=new Person("金泰妍",18,"女");
        JSONObject map=JSONObject.fromObject(p);
        String s = map.toString();
        System.out.println(s);
    }
    
    @Test
    public void fun3(){
        Person p1=new Person("抽對",20,"女");
        Person p2=new Person("taeyeon",23,"女");
        Person p3=new Person("金軟軟",26,"女");
        JSONArray list=new JSONArray();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        System.out.println(list.toString());
    }
    
    /**
     * 原來就有一個List,咱們須要把List轉換成JSONArray
     */
    @Test
    public void fun4(){
        Person p1=new Person("抽對",20,"女");
        Person p2=new Person("taeyeon",23,"女");
        Person p3=new Person("金軟軟",26,"女");
        List<Person> list=new ArrayList<Person>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        
        JSONArray a=JSONArray.fromObject(list);
        System.out.println(a.toString());
    }
}

打包ajax生成小工具---相似JQuery的ajax方法

ajaxutils.js:--->在ajax-lib包下放

// 建立request對象
function createXMLHttpRequest() {
    try {
        return new XMLHttpRequest();//大多數瀏覽器
    } catch (e) {
        try {
            return ActvieXObject("Msxml2.XMLHTTP");//IE6.0
        } catch (e) {
            try {
                return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本    
            } catch (e) {
                alert("哥們兒,您用的是什麼瀏覽器啊?");
                throw e;
            }
        }
    }
}
/*
 * option對象有以下屬性
 */
         /*請求方式*//*method,*/ 
        /*請求的url*/ /*url, */
        /*是否異步*//*asyn, */
        /*請求體*//*params, */
        /*回調方法*//*callback,*/
        /*服務器響應數據轉換成什麼類型*//*type*/

function ajax(option) {
    /*
     * 1. 獲得xmlHttp
     */
    var xmlHttp = createXMLHttpRequest();
    /*
     * 2. 打開鏈接
     */
    if(!option.method) {//默認爲GET請求
        option.method = "GET";
    }
    if(option.asyn == undefined) {//默認爲異步處理
        option.asyn = true;
    }
    xmlHttp.open(option.method, option.url, option.asyn);
    /*
     * 3. 判斷是否爲POST
     */
    if("POST" == option.method) {
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    }
    /*
     * 4. 發送請求
     */
    xmlHttp.send(option.params);
    
    /*
     * 5. 註冊監聽
     */
    xmlHttp.onreadystatechange = function() {
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//雙重判斷
            var data;
            // 獲取服務器的響應數據,進行轉換!
            if(!option.type) {//若是type沒有賦值,那麼默認爲文本
                data = xmlHttp.responseText;
            } else if(option.type == "xml") {
                data = xmlHttp.responseXML;
            } else if(option.type == "text") {
                data = xmlHttp.responseText;
            } else if(option.type == "json") {
                var text = xmlHttp.responseText;
                data = eval("(" + text + ")");
            }
            
            // 調用回調方法
            option.callback(data);
        }
    };
};

json3.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
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 'json3.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" src="<c:url value='/ajax-lib/ajaxutils.js'/>"></script>
    
    <script type="text/javascript">
        window.onload=function(){
            var btn=document.getElementById("btn");
            
            btn.onclick=function(){
                //使用ajax--傳的參數是一個對象
                ajax({
                    url:"<c:url value='/AServlet'/>",
                    type:"json",
                    callback:function(data){
                        document.getElementById("h3").innerHTML=data.name+","+data.age+","+data.sex;
                    }
                });
            };
        };
    </script>
    
  </head>
  
  <body>
      <button id="btn">點這裏</button>
    <h1>演示本身封裝的ajax小工具</h1>
    <h3 id="h3"></h3>
  </body>
</html>

AServlet:

package day23_3;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/json;charset=utf-8");
        /*
         * 向客戶端發送json字符串
         */
        String str="{\"name\":\"金泰妍\",\"age\":23,\"sex\":\"女\"}";
        System.out.println(str);
        response.getWriter().print(str);
    }
}
相關文章
相關標籤/搜索