zoukankan      html  css  js  c++  java
  • 接口返回值结果转换成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"));
           }
  • 相关阅读:
    php 安装 Redis 扩展
    远程连接mysql出现"Can't connect to MySQL server 'Ip' ()"的解决办法
    MySQL 连接超时:报错SQLSTATE[HY000] [2002] Connection timed out解决
    linux命令解压压缩rar文件
    Xshell、Xftp评估过期的解决办法
    远程连接mysql出现1045错误的解决办法
    PHP 判断当前日期是否是法定节假日或者休息日
    PHP解压压缩包文件到指定目录的实现
    PHP逐行解析文件,并写入数据库
    PHP编程实现多维数组按照某个键值排序的方法
  • 原文地址:https://www.cnblogs.com/111testing/p/6980492.html
Copyright © 2011-2022 走看看