介面傳回值結果轉換成JSON

來源:互聯網
上載者:User

標籤:hashmap   put   http請求   判斷   計數   indexof   需要   實踐   com   

介面傳回值結果轉換成JSON,具體的方法如下:

public static String GetJsonValue(String result,int index,String key){       int indexloc,indexkey;       String newstr;       indexloc=result.indexOf("[");       indexkey=result.indexOf(key);       //判斷Data域的內容       if (( indexloc>indexkey || indexloc==-1) & index==0){             JSONObject jsonObj = JSONObject.fromObject(result);             return jsonObj.getString(key);       }       else{             newstr=GetNPro(result,index);             return GetJsonValue(newstr,0,key);       }             }            public static String  GetNPro(String str,int n){       Matcher slashMatcher = Pattern.compile("\\{").matcher(str);       int mIdx = 0;       while(slashMatcher.find()) {            if(mIdx ==n){                  break;            }            mIdx++;       }       str=str.substring(slashMatcher.start(),str.length());       return str.substring(0, str.indexOf("}")+1);}

通過上面的兩個函數,我們可以將字串轉化成Json字串,並能通過關鍵字來提取對應資料。

如果要提取的資料是第一層裡面的,可以直接提取,如:GetJsonValue (jresult,0,”error”);

如果要提出的資料在data中或是更深的json中,則需要指示是第幾個資料了,資料以1開始計數,

如:GetJsonValue(jresult,2,”name”) 表示擷取第二個資料項目的name欄位的值。

藉助於這兩個函數,我們可以根據Key來提取出需要的資料,進而去做我們測試案例的判斷,完成對介面的自動化測試。當然我們還可以根據自己業務的需要,去封裝擷取你需要的資料的函數,以減少工作量。

經過上面我們封裝的調用函數,結果處理函數,就可以通過java代碼來完成對HTTP請求的API的調用,資料的擷取等功能,下面我們實踐一下:

public static void main( String[] args )    {       // Get介面調用              String url="http://api.zhongchou.cn/deal/list";        String params="?v=1";        String apiresult=GetRequests(url,params);        System.out.println("errno:"+GetJsonValue(apiresult,0,"errno"));//擷取介面傳回碼        System.out.println("name:"+GetJsonValue(apiresult,3,"name"));//擷取第三個項目的項目名稱                     //Post介面調用               String posturl="http://api.zhongchou.cn/user/login?v=1";               Map map = new IdentityHashMap ();               map.put("identity", "183****8905");                      map.put("password", "**********");                String poresult=PostRequests(posturl,map,null);               //擷取登入的使用者帳號暱稱            System.out.println("Name:"+GetJsonValue(poresult,1,"name"));       }

 

介面傳回值結果轉換成JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.