• JSON


    JSON

    1.json是什么

      * 它是js提供的一种数据交换格式!

    2.json的语法

      * { }:是对象!

        > 属性名必须使用双引号括起来!单引号不行!!!

        > 属性值:

          * null

          * 数值

          * 字符串

          * 数组:使用[ ]括起来

          * boolean值:true和false

    3.应用json

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

    代码示例:

    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);
        }
    }
  • 相关阅读:
    程序员这生必须掌握的两种图形
    用一张组织架构图说清楚类和对象
    简单工厂、工厂方法、抽象工厂的比较与分析
    rabbitmq系列(一)初识rabbitmq
    【最新】经典面试100问,附答案
    使用wordPress搭建个人博客
    调试接口你还在用postman吗
    Token ,Cookie、Session傻傻分不清楚?
    你不可不知的自定义注解
    使用aop加解密http接口
  • 原文地址:https://www.cnblogs.com/xjs1874704478/p/11010619.html
Copyright © 2020-2023  润新知