Jmeter - Beanshell 获取响应结果(json数据)中某个字段的值

jmeter http请求响应报文为 json格式, 数据如下:

DataFunc([{"TID":"1264","retCode":"17"},{"TID":"1270","retCode":"17"},{"TID":"1253","retCode":"17"},{"TID":"1252","retCode":"17"},{"TID":"1251","retCode":"17"},{"TID":"1250","retCode":"17"},{"TID":"1249","retCode":"17"},{"TID":"1259","retCode":"17"},{"TID":"1258","retCode":"17"},{"TID":"1269","retCode":"17"},{"TID":"1255","retCode":"17"},{"TID":"1268","retCode":"17"},{"TID":"1267","retCode":"17"},{"TID":"1257","retCode":"17"},{"TID":"1266","retCode":"17"},{"TID":"1256","retCode":"17"},{"TID":"1265","retCode":"17"}])

1、导入 net.sf.json.* 所需要的包:json-lib-2.4-jdk15.jar

2、TID这个json数组的信息是下一个请求所需要的request信息中的一部分。

那么在‘优先级计算’这个sampler上添加一个 BeanShell PostProcessor, 就可以获取这段json信息, 然后通过vars.put("result ",Arrays.toString(result) ); 将信息保存到全局变量中。
Arrays.toString(result) 返回指定数组内容的字符串表示形式。

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

String response_data = prev.getResponseDataAsString();
String response_data1 = response_data.substring(9,response_data.length()-1);
JSONArray tidArray = JSONArray.fromObject(response_data1);
System.out.println(tidArray.size());
String [] result = new String[tidArray.size()];
for(int i=0;i

3、输出如下:

image.png

4、多个节点,如下处理:

 {
"priorityGroups": {
"promotionId": 1364,
"name": "促销03",
 "groups": [
 {
 "groupId": "a7358a0a-78a1-4418-bb7a-bb752e32295f",
  "items": [
  {
  "promotionId": 1364,
         "name": "促销03",
         "index": 1
  },
 {
  "promotionId": 1361,
  "name": "单品2",
  "index": 2
 },
 {
 "promotionId": 1358,
  "name": "单品促销-09-指定多个商品-N件X折-1358",
  "index": 4
  }
  ]
  }
 ]
}

}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

String jsonContent = prev.getResponseDataAsString();
JSONObject response = new JSONObject(jsonContent);
JSONArray groups = response.getJSONObject("priorityGroups").getJSONArray("groups");
String strGroups = groups.toString();
 vars.put("groups",strGroups);

你可能感兴趣的:(Jmeter - Beanshell 获取响应结果(json数据)中某个字段的值)