准备工作:
将json-20160212.jar 放入jmeter的lib目录下, 或者在脚本中添加其所在的classpath
jar包可以通过maven获取:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
举例来说:
‘优先级计算’ 是一个http请求, 其返回结果为一段json:
- {
- "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
- }
- ]
- }
- ]
- },
- "promotion": {
- "promotionId": 1364,
- "parentId": null,
- "customerId": 84,
- "name": "促销03",
- "subjectId": null,
- "from": 1470821215000,
- "to": 1470907615000,
- "enterType": 1,
- "hasCoupon": 1,
- "promoType": 2,
- "isTemplate": 0,
- "memo": null,
- "status": 1,
- "objectScopeId": 1069,
- "createBy": 394,
- "sourceId": 1364,
- "editStatus": null,
- "effectiveTime": 1470821215000,
- "createTime": 1470821155000
- }
- }
那么在‘优先级计算’这个sampler上添加一个 BeanShell PostProcessor, 就可以获取这段json信息, 然后通过vars.put("groups",strGroups); 将信息保存到全局变量中。
- 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);
最后, 在下一个请求的request body中使用这段信息