首页 > 代码库 > 接口返回值结果转换成JSON
接口返回值结果转换成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")); }
接口返回值结果转换成JSON
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。