接口返回值轉成json

接口返回值結果轉換成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"));
       }

複製代碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章