Beanshell parsing and extracting json response for Jmeter performance test

1: Precondition

Place the fastjson-1.2.49.jar package in the lib directory of jmeter, and add the jar package to the library of the test plan; otherwise, it will report: Typed variable declaration: Class: JSONObject not found in namespace error

2: Analyze ideas

Use beanshell to get the json response, then parse the array through JSONObject and JSONArray, and extract the parameter value after traversing the length of the array

We need to parse the following json response to extract the middle Name and population

//导入json包
import org.json.*;
//获取获取请求的返回值
String response_data = prev.getResponseDataAsString();
//日志打印获取请求的返回值
log.info(response_data);
//将String类型的返回值构造成JSONObject对象
JSONObject data_obj = new JSONObject(response_data);

//获取作为下一个请求post的参数值Province(两种方式)
//String Provincelist_str = data_obj.get("Province").toString();
JSONArray Provincelist_str = data_obj.getJSONArray("Province");
//log.info(Provincelist_str);

//获取Province数组的长度
int len = Provincelist_str.length();

String strlen = Integer.toString(len);

vars.put("MessageNum",strlen);

log.info(strlen);

int i = 0;

for(;i < len;++i)
{
//获取 data[ i ] 数组对象
JSONObject jsonTemp = (JSONObject)Provincelist_str.getJSONObject(i);

switch(i)

{
case 0:
//两种提取参数的写法
String NameItems = jsonTemp.getString("Name");
// String NameItems = jsonTemp.get("Name").toString();

// 两种打印参数的方法
// vars.put("Name_1", jsonTemp.getString("Name"));
vars.put("Name_1", NameItems);
log.info(NameItems);

}
}

After adding debug, it is found that two sets of data have been extracted, namely province and population, which can be called in subsequent interfaces

Guess you like

Origin blog.csdn.net/lovedingd/article/details/131922700