zoukankan      html  css  js  c++  java
  • json

      JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。通常是服务器和浏览器交互数据的一种格式。
    json在js中的使用:
    json语法:
    json对象:{key:value,key2:value}
    json数组:[{key:value , key2 :value2 } , {key:value3 , key2 :value4 }]
    1、json在js中的使用

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'json-01.jsp' starting page</title>
    13     
    14     <meta http-equiv="pragma" content="no-cache">
    15     <meta http-equiv="cache-control" content="no-cache">
    16     <meta http-equiv="expires" content="0">    
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    18     <meta http-equiv="description" content="This is my page">
    19     <!--
    20     <link rel="stylesheet" type="text/css" href="styles.css">
    21     -->
    22 
    23   </head>
    24   
    25   <body>
    26     json在js中的使用:<hr>
    27   </body>
    28   <script type="text/javascript">
    29       /* 
    30       json语法:
    31           json对象:{key:value,key2:value}
    32           json数组:[{key:value , key2 :value2 } , {key:value3 , key2 :value4 }] 
    33       */
    34       //定义一个json的字符串【两种方式转换】
    35       var jsonStr1 = '{"name":"josn","pwd":12346}';//JSON.parse(jsonStr1);[注意:json字符串 必须是 单引号]
    36       var jsonStr2 = "{'name':'josn','pwd':12346}";//eval("var str2Obj2 = "+jsonStr2);
    37       //定义一个json对象
    38       var jsonObj = {'name':'admin','pwd':123465};
    39       console.log("取出name属性值:"+jsonObj.name);
    40       /**
    41       *json字符串和json对象间的互转
    42       */
    43       //json字符串转成json对象
    44       var str2Obj1 = JSON.parse(jsonStr1);
    45       console.log(str2Obj1);
    46       eval("var str2Obj2 = " +jsonStr2 );
    47       
    48       //查看变量的类型:typeof
    49       console.log( typeof str2Obj2);//object
    50       
    51       /**
    52       *将json对象转换成json字符串
    53       */
    54       var obj2Str = JSON.stringify(str2Obj2);
    55       console.log(obj2Str);
    56       console.log(typeof obj2Str);//string
    57       
    58   </script>
    59 </html>
    View Code

    2、json在java中的使用:java中如果没有工具jar包:json本质是一个字符串
    1: 利用json的工具包将 字符串和json对象互转 
    2:json格式和javabean对象(实体类对象)的相互转换
    3:json格式和list的相互转换
    gson  jar 包


    TestJSON

    3、测试 servlet和ajax交互 使用json格式

     1 package boom.json.servlet;
     2 
     3 import java.io.IOException;
     4 import java.util.ArrayList;
     5 import java.util.List;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 import boom.json.bean.Student;
    13 
    14 import com.google.gson.Gson;
    15 /**
    16  * 测试 servlet和ajax交互 使用json格式
    17  * 
    18  * json格式 如何实现java代码和js代码的相互交换的
    19  *         servlet和  js的ajax进行交互
    20  * url:/testJsonServlet.boom
    21  * @author Administrator
    22  *
    23  */
    24 public class TestJsonServlet extends HttpServlet {
    25     @Override
    26     protected void service(HttpServletRequest request, HttpServletResponse response)
    27             throws ServletException, IOException {
    28         // 创建list学生对象
    29         List<Student> students = new ArrayList<>();
    30         // 添加测试数据
    31         Student stu1 = new Student(1, "Dilraba", "女", 100);
    32         Student stu2 = new Student(2, "小喜庆", "女", 101);
    33         Student stu3 = new Student(3, "小明", "男", 99);
    34         students.add(stu1);
    35         students.add(stu2);
    36         students.add(stu3);
    37 
    38         // 将list转换成json格式
    39         Gson gson = new Gson();
    40         String listJSON = gson.toJson(students);
    41         
    42         //传给前端页面
    43         response.setContentType("text/json;charset=utf-8");
    44         response.getWriter().println(listJSON);
    45     }
    46 }
    TestJsonServlet
     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%
     3 String path = request.getContextPath();
     4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     5 %>
     6 
     7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     8 <html>
     9   <head>
    10     <base href="<%=basePath%>">
    11     
    12     <title>My JSP 'testJsonServlet.jsp' starting page</title>
    13     
    14     <meta http-equiv="pragma" content="no-cache">
    15     <meta http-equiv="cache-control" content="no-cache">
    16     <meta http-equiv="expires" content="0">    
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    18     <meta http-equiv="description" content="This is my page">
    19     <!--
    20     <link rel="stylesheet" type="text/css" href="styles.css">
    21     -->
    22 
    23   </head>
    24   
    25   <body>
    26     <script type="text/javascript" src="js/ajaxutil.js"></script>
    27     <script type="text/javascript">
    28         ajaxutil("post", //请求方式  post get  
    29         "testJsonServlet.boom", // 请求的服务器的地址 servlet的url
    30         true, // 是否异步
    31         null,//参数  客户端提交给服务器端的参数  ajax ---->servlet的参数
    32         function handler200(xhr) {//服务器返回给 客户端的数据  servlet--->ajax 页面的数据
    33             //获取  servlet响应给前端页面的json数据    
    34             var rsData = xhr.responseText;
    35             console.log("rsData:" + typeof rsData);
    36 
    37             //将json str转换成json对象
    38             eval("var studentArr= "  + rsData);
    39             for ( var i in studentArr) {
    40                 var stu = studentArr[i];
    41                 console.log(stu.name + "----" + stu.id);
    42             }
    43         });
    44     </script>
    45 </body>
    46 </html>
    testJsonServlet.jsp
    /**
     * 
     *         <script type="text/javascript" src="ajaxutil.js"></script>
            <script type="text/javascript">
            
    
            function  testAjax(){
                 ajaxutil("get",
                        "testAjaxUtil.bjsxt?name=admin",
                        true, 
                        "cmd=add"
                        , 
                        //function (){}//可以传一个函数  ,处理 200响应
                        function handler200(xhr){//获取  servlet服务器端的返回结果
                            //响应成功
                            //获取数据 
                            var rsData = xhr.responseText;
                                alert(rsData);
                        },
                        function handler404(){
                            alert("404 。。。。。页面丢失le......");
                        },
                        function handler500(){
                            alert("服务器正在维护......");
                        }
                    );
             
            }
     * 
     * 
     */
    
            //     method      url   async    参数  args  
            // 响应结果 处理方式 不同    handler200 handler404 handler500
            
            function  ajaxutil(method , url , async , args , handler200,handler404 ,handler500){
                
                var str ;
                /*1 创建ajax 的引擎对象XMLHttpRequest  */
                var xhr ; 
                //判断是否是IE5,IE6
                if(window.XMLHttpRequest){
                     xhr = new XMLHttpRequest();
                }else{//判断是否是IE5,IE6  ActiveXObject
                    xhr =new ActiveXObject("Microsoft.XMLHTTP");
                }
            
                //为了防止浏览器缓存  ,所以加上new Date().getTime()随机数设置
                xhr.onreadystatechange =function(){
                    if(xhr.readyState==4){
                        
                        //     method      url   async    参数  args  
                        // 响应结果 处理方式 不同    handler200 handler404 handler500
                        if(xhr.status == 200 ){
                            // xhr XMLHttpRequest对象
                            handler200(xhr);
                        }else if(xhr.status == 404){
                            handler404();
                            //alert("您访问的页面去火星了......");
                        }else if(xhr.status == 500){
                            handler500();
                            //alert("您访问服务器正在维护......");
                        }
                    }
                }
                
            
                
                
                //处理get,post请求
                if("get"==method.toLocaleLowerCase()){
                    
                    //一般省略  ???? 
                    if(url.indexOf("?")==-1){
                        xhr.open(method, url+"?"+args, async);
                    }else{
                        xhr.open(method, url+"&"+args, async);
                    };
                    
                    xhr.send(null);
                }else{
                    xhr.open(method, url , async);
                    //请求之前设置编码集 
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    //3  向服务器发送请求数据  get请求无法用send方法发送数据  ,所以默认是null
                    xhr.send(args);
                }
                //非ajax方法  获取不到返回值
                //return  str;
    
            };
    ajaxutil
  • 相关阅读:
    [LeetCode] 226. Invert Binary Tree
    [LeetCode] 101. Symmetric Tree
    [LeetCode] 100. Same Tree
    [LeetCode] 104. Maximum Depth of Binary Tree
    [LeetCode] 280. Wiggle Sort
    [LeetCode] 42. Trapping Rain Water
    [LeetCode] 190. Reverse Bits
    [LeetCode] 144. Binary Tree Preorder Traversal
    [Leetcode] 58. Length of Last Word
    [LeetCode] 16. 3Sum Closest
  • 原文地址:https://www.cnblogs.com/cao-yin/p/9838653.html
Copyright © 2011-2022 走看看