使用beanshell在jmeter中获取json响应
在我的jmeter响应中,我有javascript和json作为混合响应,我必须获取一个JSON数组,
items
这是我得到的巨大响应的一部分
DE.APP.task.TaskGrid.getAssignmentData = function () { return {"items":[]};
};
DE.APP.task.TaskGrid.getResourceData = function () {
return {"items":[{"STANDARDRATEFORMAT":"0.00","ASSIGNED_HRS":0,"RESOURCE_NAME":"#Buddhika ","COST":"0.00","PERCENTASSIGNED":"100.00","EMAIL":"Buddhika75@mspblank.com","AVAILABLEFROM":"10-May-2011","ALLOCATED_HRS":"1872.00","RESOURCE_ID":36197221,"AVAILABLETO":"31-Mar-2012","calendar":{"exceptions":{},"weekDayHours"
在此响应中,我必须获取getResourceData()中的json数组,而不是其他任何项目。我们如何用beanshell攻击做到这一点?
回答:
您可以使用apache StringUtils使用左边界和右边界来切割字符串。您的左边界是清晰的“ return
{”,但我不确定您的右边界(JSON有效负载之后的字符串)。在下面的示例中,我使用]}作为分隔符来剪切JSON有效负载。使用prev.getResponseDataAsString()将响应有效负载拉为字符串。
import org.apache.commons.lang3.StringUtils;import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;
String sInputString = "return {\"items\":[{\"STANDARDRATEFORMAT\":\"0.00\",\"ASSIGNED_HRS\":0,\"RESOURCE_NAME\":\"#Buddhika \",\"COST\":\"0.00\",\"PERCENTASSIGNED\":\"100.00\",\"EMAIL\":\"Buddhika75@mspblank.com\",\"AVAILABLEFROM\":\"10-May-2011\",\"ALLOCATED_HRS\":\"1872.00\",\"RESOURCE_ID\":36197221,\"AVAILABLETO\":\"31-Mar-2012\",\"calendar\":{\"exceptions\":{},\"weekDayHours\":{}}}]}";
//String sInputString = prev.getResponseDataAsString();
try {
// Use StringUtils to cut the string between the two
String sCutString = StringUtils.substringBetween(sInputString, "return {\"items", "]}");
String sFinalString = "{\"items" + sCutString + "]}";
log.info("sFinalString=" + sFinalString);
// Use JSONParser to parse the JSON
JSONParser parser = new JSONParser(JSONParser.ACCEPT_NON_QUOTE|JSONParser.ACCEPT_SIMPLE_QUOTE);
JSONObject rootObject = (JSONObject) parser.parse(sFinalString);
//JSONObject rootObject = (JSONObject) parser.parse(prev.getResponseDataAsString());
JSONArray jResourceArray = (JSONArray) rootObject.get("items");
for (int i=0; i < jResourceArray.size(); i++) {
log.info(jResourceArray.get(i).toString());
// You can access individual elements using this
log.info("RESOURCE_ID=" + jResourceArray.get(i).get("RESOURCE_ID"));
}
}
catch ( Exception ex) {
log.info("Exception.." + ex);
}
以上是 使用beanshell在jmeter中获取json响应 的全部内容, 来源链接: utcz.com/qa/415944.html