json的使用原理及執行個體

來源:互聯網
上載者:User

這次在項目中前背景資料互動中用到了json,經過這段時間的使用,大概瞭解了一下,簡單總結一下json。
JSON:JavaScript 物件標記法(JavaScript Object Notation)。
JSON 是儲存和交換文本資訊的文法。類似 XML。
JSON 比 XML 更小、更快,更易解析。
和 XML 一樣,JSON 也是基於純文字的資料格式。由於 JSON 天生是為 JavaScript 準備的,因此,JSON 的資料格式非常簡單,您可以用 JSON 傳輸一個簡單的 String,Number,Boolean,也可以傳輸一個數組,或者一個複雜的 Object 對象。
先看controller中的一段代碼。看主要是看從資料庫查詢出來的資料是怎樣以json的格式輸出的。
[java] 
@RequestMapping("/work/plan/checkSubmitForApproval") 
public void checkSubmitForApproval(String planId,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{ 
    String result="{\"result\":\"faild\",\"personSituation\":\"null\"}";     
    HttpSession session = request.getSession(); 
    String industryID = (String) session.getAttribute("industryID");  
    IIndustry industry = industryService.getById(industryID); 
        if(industry.getType().equals("XXX")){ 
        try { 
            boolean flag = false; 
            IProjectMain yearPlan = projectPlanService.findProjectPlanById(planId); 
                List<IStaffInfo> listStaffInfo = sysStaffService.getStaffByPlanId(planId, industryID); 
                for(int i=0;i<listStaffInfo.size();i++){ 
                    if(listStaffInfo.get(i).getPractitionersPost().equals(StaffRole.PROGECTMANAGER.toString())){ 
                        flag = true; 
                    } 
                } 
                if(flag == true){ 
                    result="{\"result\":\"success\",\"personSituation\":\""+yearPlan.getPerson_Situation()+"\"}"; 
                }else{ 
                    result="{\"result\":\"success\",\"personSituation\":\""+yearPlan.getPerson_Situation()+"\",\"isManager\":\"false\"}"; 
                } 
                 
            } catch (Exception e) { 
                result="{\"result\":\"falid\"}"; 
                throw new PlatformException(e); 
            }finally{ 
                OutputUtils.write(response,result,"text/x-json;charset=UTF-8"); 
            } 


先PutputUtils中的write代碼:
[java] 
public static void write(HttpServletResponse response, String text, String contentType) 
   { 
    PrintWriter out=null; 
    response.setHeader("Pragma", "No-cache"); 
    response.setHeader("Cache-Control", "no-cache"); 
    response.setDateHeader("Expires", 0); 
       response.setContentType(contentType); 
     
       try 
       { 
        out = response.getWriter(); 
        out.write(text); 
       } 
       catch (IOException e) 
       { 
           Logger.getLogger(OutputUtils.class).error(e.getMessage(), e); 
       } finally{ 
        if(out!=null){ 
            out.flush(); 
            out.close(); 
        } 
    } 
   } 

其中的思路是得到response的printwriter,將要輸出的資訊設定到其中。在介面層利用jquery的Post判斷返回的資訊。
[javascript] 
<span style="white-space:pre">  </span>function distribute(){ 
        var dplanId = $(".currli").attr("id"); 
        if(dplanId != ""){ 
            $.ajax({ 
                type : "POST", 
                url :做驗證的action url, 
                dataType : "json", 
                success : function(data) { 
                    //HAVE為已指派狀態 
                    if (data.result == "success" && data.personSituation == "UNHAVE") {  
                        with (document.getElementById("planForm")) { 
                            action=驗證合法後要提交的url; 
                            method="post"; 
                            submit(); 
                        } 
<span style="white-space:pre">              </span>} 
其中success:function(data)是一個回呼函數,即上面做的驗證action的方法成功之後執行的操作。在jquery的使用方法詳情點擊這裡查看。
關於jquery的post提交不理解的同學,點擊這裡學習。
關於ajax和jquery的曆史,建議參見維基百科中,寫的很清楚。
jquery已經封裝好了從response中取data的操作,所以這裡用起來非常方便,省去了從xml中一點一點讀取的頭疼,給開發帶來了極大方便。

 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.