Jmeter BeanShell PostProcessor提取json数据
需求:提取sample返回json数据中所有name字段值,返回的json格式如下:
{“body”:{“apps”:[{“name”:”111”},{“name”:”222”}]}}
jmeter中添加后置处理器BeanShell PostProcessor
import org.json.*;
String response_data = prev.getResponseDataAsString();
JSONObject data_obj = new JSONObject(response_data);
String apps_str = data_obj.get("body").get("apps").toString();
JSONArray apps_array = new JSONArray(apps_str);
String[] result = new String[apps_array.length()];
for(int i=0;i<apps_array.length();i++){
JSONObject app_obj = new JSONObject(apps_array.get(i).toString());
String name = app_obj.get("name").toString();
result[i] = name;
}
vars.put("result", Arrays.toString(result));
JSONObject和JSONArray遍历数组与对象
JSONObject和JSONArray的API链接:
1、识别json格式字符串是JSONObject还是JSONArray
JSON数据格式只有两种形式,分别是:
{
"key"
:
"value"
}
//JSONObject(对象)
[{
"key1"
:
"value1"
}, {
"key2"
:
"value2"
}]
//JSONArray(数组)
JSONObject可以用key取值,JSONArray只能遍历取值
2、遍历json数组
假设我们得到的json字符串result如下:
{
"feature"
:
"fresh_today"
,
"photos"
:[
{
"id"
:
40581634
,
"name"
:
"Dandelion 5"
},
{
"id"
:
40581608
,
"name"
:
"Dandelion 3"
}
]
}
可以看出来,最外面是个json对象,photos节点是个数组,遍历代码如下:
import
net.sf.json.JSONArray;
import
net.sf.json.JSONObject;
JSONObject jsonObject = JSONObject.fromObject(result);
String feature = jsonObject.getString(
"feature"
);
JSONArray photoArray = jsonObject.getJSONArray(
"photos"
);
for
(
int
i =
0
; i < photoArray.size(); i++) {
JSONObject object = (JSONObject) photoArray.get(i);
int
id = object.getInt(
"id"
);
String name = object.getString(
"name"
);
}