接口返回值结果转换成JSON

本文介绍了一种将接口返回结果转换为JSON格式的方法,并提供了通过关键字提取所需数据的具体实现。通过两个自定义函数GetJsonValue和GetNPro,可以轻松处理多层嵌套的JSON数据,适用于接口自动化测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接口返回值结果转换成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"));
       }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值