Java基礎——JSON

1、JSON定義javascript

在百度百科中的解釋:JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式。它基於JavaScript的一個子集。 JSON採用徹底獨立於語言的文本格式,JSON簡單說就是javascript中的對象和數組,因此這兩種結構就是對象和數組兩種結構,經過這兩種結構能夠表示各類複雜的結構。html

一、對象:java

對象在js中表示爲「{}」括起來的內容,數據結構爲 {key:value,key:value,...}的鍵值對的結構,在面向對象的語言中,key爲對象的屬性,value爲對應的屬性值,因此很容易理解,取值方法爲 對象.key 獲取屬性值,這個屬性值的類型能夠是 數字、字符串、數組、對象幾種。jquery

二、數組:web

數組在js中是中括號「[]」括起來的內容,數據結構爲 ["java","javascript","vb",...],取值方式和全部語言中同樣,使用索引獲取,字段值的類型能夠是 數字、字符串、數組、對象幾種。簡單地說,JSON 能夠將 JavaScript 對象中表示的一組數據轉換爲字符串,而後就能夠在函數之間輕鬆地傳遞這個字符串,或者在異步應用程序中將字符串從 Web 客戶機傳遞給服務器端程序。這個字符串看起來有點兒古怪,可是JavaScript很容易解釋它。ajax

之前學過的jquery 遍歷   Dictionary 風格的數組(其實就是一個javascript對象)數據庫

var stu={ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
    $.each(stu,function(key,value){
        alert(key+"---"+value);
    })
    
    
    var people = 
      {
          "演員": 
          [ 
              { "firstName": "Brett", "lastName":"要被取值的", "email": "aaaa" },
                { "firstName": "Jason", "lastName":"Hunter", "email": "bbbb" },
                { "firstName": "Elliotte", "lastName":"Harold", "email": "cccc" }
            ],
            
            "做者": [
            { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
            { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
            { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
            ],
            
            "配樂": [
            { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
            { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
            ] 
        
        }
        
        //這裏有3 個key,每一個key對應的value 又是一個數組,數組中的每一個元素,又是一個對象(對象由鍵值對組成)
        //alert(people.演員[0].lastName) ; 能夠取出 "要被取值的" 這個數組
//例子 用JSON 傳輸數據
        
        //客戶端
        $(function(){
            $("button").click(function(){
                $.ajax({
                    url:"JSONTestServlet",  
                    type:"post",
                    data:{userName:$("#userName").val()},
                    dataType:"JSON",   //千萬不要忘了指定返回數據的格式
                    success:function(user){
                        $("#divresult").append("用戶id:"+user.id +"<br />");
                        $("#divresult").append("用戶名:"+user.userName +"<br />");
                        $("#divresult").append("用戶密碼:"+user.password +"<br />");
                        $("#divresult").append("用戶備註:"+user.note +"<br />");
                    }
                });
            });
        });
        
    
        
        //服務端
     public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
            //這裏,要把 user轉JSON格式的字符串返回
            String str=" {\"id\":\"1\",\"userName\":\"張三\",\"password\":\"admin\" ,\"note\":\"這是備註\"} ";
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(str);    
        }

2、JSONlib 的使用(兩步) 跨域

1) 導入 JSON lib的包數組

commons-beanutils-1.8.2.jar服務器

commons-collections-3.2.1.jar

commons-lang-2.5.jar

commons-logging-1.1.1.jar

ezmorph-1.0.6.jar

JSON-lib-2.4-jdk15.jar

2) 使用

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            String userName=request.getParameter("userName");
            UserInfo user= UserDao.getUserByName(userName);
            //使用JSONlib提供的功能,將一個類對象轉成JSON格式的字符串
            JSONObject JSONObj=JSONObject.fromObject(user);
            System.out.println(JSONObj);
            
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print(JSONObj.toString());    
        }
    }
//例子,如何使用 JSONlib 返回一組數組
     //服務端
         public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            List<UserInfo> userList=UserDao.getAllUser();
            
            //若是要轉一個對象, 用JSONObject,轉多個對象(List),用 JSONArray 
            JSONArray JSONObj= JSONArray.fromObject(userList);
            
            response.setContentType("text/html;charset=utf-8" );
            response.getWriter().print(JSONObj);
     }
     
     //客戶端
         $(function(){
            $("button").click(function(){
                $.ajax({
                    url:"JSONArrayTestServlet",  
                    type:"post",
                    dataType:"JSON",  
                    success:function(userList){
                        
                    //取出數據的第一種方式
                    /*     for(var i=0;i<userList.length;i++){
                            alert(userList[i].id);
                            var trStr="<tr><td>"+userList[i].id+"</td><td>"+userList[i].userName+
                            "</td><td>"+userList[i].password+"</td><td>"+userList[i].note+"</td></tr>"; 
                            $("#table1").append(trStr);
                        } */
                        
                        
                        //使用 $.each() 的方式
                        $.each(userList,function(key,user){
                             var trStr="<tr><td>"+user.id+"</td><td>"+user.userName+
                            "</td><td>"+user.password+"</td><td>"+user.note+"</td></tr>"; 
                            $("#table1").append(trStr); 
                        });
                    }
                });
            });
        });
//例子 將JSON字符串反序列化爲 java對象
  String JSONStr= "{\"id\":99,\"userName\":\"張三\",\"password\":\"admin\",\"note\":\"備註\",\"aihao\":\"球類\"}" ;
  JSONObject JSONObj=JSONObject.fromObject(JSONStr);
            
//注意,UserInfo 類,必定要有一個無參的構造函數
  UserInfo user=(UserInfo)JSONObject.toBean(JSONObj,UserInfo.class);

3、Ajax聯動菜單

    //請求發起頁面
        $(function(){
            $("#bigCate").change(function(){
                //取出本身的被選中的option 的 value (它應該是小分類對應的parentId)
                var parentId=this.value ;
                
                //根據這個parentId去數據庫查詢,
                $.ajax({
                    url:"CateAjaxServlet",
                    cache:false,
                    data:{parentId:parentId},
                    dataType:"JSON",
                    success:function(cateList){
                        //把取務端返回的小分類的列表,拼到小分類對應的下拉框中,但要先清空一下
                        $("#smallCate").empty();
                        $.each(cateList,function(key,cateInfo){
                            var optionStr="<option value='"+cateInfo.id+"'>"+cateInfo.cateName+"</option>";
                            $("#smallCate").append(optionStr);
                        });
                        
                    }
                });    
            });
        });
        
        <body>
      <%
          List<CateInfo> bigCateList=new CateDao().getCateList(0);
          request.setAttribute("bigCateList", bigCateList);
       %>
       <form action="xxx" method="post">
           大分類:
           <select id="bigCate" name="bigCate" >
               <c:forEach var="cateInfo" items="${ bigCateList}" >
                   <option value="${cateInfo.id }">${cateInfo.cateName }</option>
               </c:forEach>
           </select>
           
           小分類:
           <select id="smallCate" name="smallCate" >
           </select>
           
            打醬油的:
           <input type="text" />
       </form>
   </body>
        
   //服務端
   public void doPost(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException {
   //根據傳上來的parentID 查詢子分類
         int parentId = Integer.parseInt(request.getParameter("parentId"));
         List<CateInfo> cateList=new  CateDao().getCateList(parentId);
         
JSONArray JSONObj
=JSONArray.fromObject(cateList); response.setContentType("text/html;charset=utf-8" ); response.getWriter().print(JSONObj); }

4、關於返回數據類型 爲 JSONp 的狀況

由於同源策略,Ajax  的請求是不準跨域訪問的,若是試圖訪問其餘服務器上的url 會出現以下錯誤

1.已阻止交叉源請求:同源策略不容許讀取 http://10.10.10.15:8080/JSONPDemo/TestServlet 上的遠程資源。

解決方法:能夠將資源移動到相同的域名上或者啓用 CORS 來解決這個問題。

2.已阻止跨源請求:同源策略禁止讀取位於 http://169.254.246.250:8080/web1/WebAServlet 的遠程資源。(緣由:CORS 頭缺乏 'Access-Control-Allow-Origin')。

同源策略是指阻止代碼得到或者更改從另外一個域名下得到的文件或者信息。也就是說咱們的請求地址必須和當前網站的地址相同。同源策略經過隔離來實現對資源的保護。這個策略的歷史很是悠久從Netscape Navigator 2.0時代就開始了。

解決方法:解決這個限制的一個相對簡單的辦法就是在服務器端發送請求,服務器充當一個到達第三方資源的代理中繼。雖然是用普遍可是這個方法卻不夠靈活。

另外一個辦法就是使用框架(frames),將第三方站點的資源包含進來,可是包含進來的資源一樣要受到同源策略的限制。有一個很巧妙的辦法就是在頁面中使用動態代碼元素,代碼的源指向服務地址並在本身的代碼中加載數據。當這些代碼加載執行的時候,同源策略就不會起到限制。可是若是代碼試圖下載文件的時候執行仍是會失敗,幸運的是,咱們可使用JSON(JavaScript Object Notation)來改進這個應用。

//JSONp的使用
<script type="text/javascript">
    $(function(){
    $("button").click(function(){
        $.ajax({
            url:"http://169.254.246.250:8080/web1/WebAServlet",
            dataType:"JSONp",       //這裏使用 JSONp這個格式
            JSONp:"JSONpcallback",  //這個名字是給別人用的
            success:function(data){
                $("#div1").append(data.id+"<br />");
                $("#div1").append(data.userName+"<br />");
                $("#div1").append(data.password+"<br />");
                $("#div1").append(data.note+"<br />");
                        }
                    });
                });
            });
</script>
        
        
//被訪問者的服務端
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        String JSONp=request.getParameter("JSONpcallback");
        String JSONStr= "{\"id\":99,\"userName\":\"張三\",\"password\":\"admin\",\"note\":\"備註\",\"aihao\":\"球類\"}" ;
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print( JSONp+"("+   JSONStr  +")" );     
}
相關文章
相關標籤/搜索