Jmeter获取接口返回数组的长度
添加BeanShell PostProcessor来获取,具体代码如下:
1 import com.jayway.jsonpath.JsonPath; 2 import com.jayway.jsonpath.Predicate; 3 import net.minidev.json.JSONArray; 4 public class Test { 5 public static String readjson(String json, String jsonPath) { 6 try 7 { 8 Object value = JsonPath.read(json, jsonPath, new Predicate[0]); 9 if (value instanceof Integer) 10 { 11 return value.toString(); 12 }else if (value instanceof String) 13 { 14 return value.toString(); 15 }else if (value instanceof Boolean) 16 { 17 return value.toString(); 18 }else if (value instanceof JSONArray) 19 { 20 JSONArray arr = (JSONArray)value; 21 if(!arr.isEmpty()){return arr.toJSONString();} 22 return ""; 23 }else if (value instanceof LinkedHashMap) 24 { 25 return value.toString(); 26 }else if (value instanceof float) 27 { 28 return value.toString(); 29 }else{ 30 return value.toString(); 31 } 32 } 33 catch(Exception e){ 34 return "pathnotfound"; 35 } 36 } 37 } 38 //------------------------------------------------------------------------------------------------------------------ 39 public static void fun(){ 40 String response_data=prev.getResponseDataAsString();//prev为JMeter预定义变量 41 String JsonPath="$.data.list.length()"; 42 String result=Test.readjson(response_data,JsonPath); 43 int resultToNum=Integer.parseInt(result); 44 log.info("------------------------返回数组的长度为:"+result+"----------------------"); 45 vars.put("ResultTotal",result); 46 } 47 fun();