我正在尝试使用 Beanshell 后处理器提取 JSON 数组的一个变量的值,但在日志中没有收到任何响应
我的 JSON 看起来像:
"store":
: [
: : {
: : : "storeId":12345,
: : : "storeName":"ABC",
: : : "storeAddress":"DEFGHIJKL",
: : : "storeMinOrderAmount":100,
: : : "mobile":"+911234567890",
: : : "mobileSecondary":null,
: : : "city":"Somewhere",
: : : "pincode":123456,
: : : "country":"India",
: : : "email":"[email protected]",
: : : "pickup":true,
: : : "delivery":false,
: : : "storeSplashPath":null,
: : : "storeSplashType":null,
: : : "distance":"0.10"
: : },
我的 Beanshell 后处理器是:
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.eclipsesource.json.*;
print("*******************");
//Get Store total count
int totalStoreNumber = StringUtils.countMatches(new String(data), "storeId");
print("Total Number of Stores are: " + totalStoreNumber);
if (totalStoreNumber > 0) {
//Check for Fulfilment type is "Pickup"
String jsonString = prev.getResponseDataAsString();
JsonObject store = JsonObject.readFrom(jsonString);
JsonArray store = store.get("store").asArray();
String pickup = store.get(1).asObject().get("pickup").asString();
vars.put("fulfilmentType_BSH", pickup);
print("Is Pickup allowed: " + pickup);
}
else {
print("No Stores Nearby");
}
我不知道我哪里错了。我已阅读相关查询,但无法正确理解。
任何想法?
首先,你为什么不使用JSON 路径后处理器为了它?您可以使用单个简单的方法获得完全相同的结果JSON 路径表达式如:
$.store[0].pickup
如果出于某种原因你仍然需要在 Beanshell 中执行此操作,我有一些想法:
-
这绝对是错误。不能在 Beanshell 脚本中声明 2 个同名变量
JsonObject store = JsonObject.readFrom(jsonString);
JsonArray store = store.get("store").asArray();
// ^^^^^ ka-boom!
-
可能的问题。索引越界异常如果响应中只有 1 个商店。在 Beanshell 中,集合是从零开始的,第一个元素的索引为 0。
String pickup = store.get(1).asObject().get("pickup").asString();
// ^ ka-boom!
-
另一个可能的问题可能与您的进口有关,以防万一
import org.json.JSONArray;
import org.json.JSONObject;
import com.eclipsesource.json.*;
你是否添加了相关的jarJMeter 类路径之后你重新启动JMeter了吗?您确定您使用的方法正确吗?
这是您使用重新实现的代码json-智能JMeter 3.0 附带(你不需要任何其他 jars)
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.apache.commons.lang.StringUtils;
//Get Store total count
int totalStoreNumber = StringUtils.countMatches(new String(data), "storeId");
log.info("Total Number of Stores are: " + totalStoreNumber);
if (totalStoreNumber > 0) {
//Check for Fulfilment type is "Pickup"
String jsonString = new String(data);
JSONParser parser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
JSONObject store = (JSONObject) parser.parse(data);
JSONArray storeArray = (JSONArray) store.get("store");
String pickup = ((JSONObject) storeArray.get(0)).getAsString("pickup");
vars.put("fulfilmentType_BSH", pickup);
log.info("Is Pickup allowed: " + pickup);
} else {
log.info("No Stores Nearby");
}
及其工作的证据
See 如何使用 BeanShell:JMeter 最喜欢的内置组件有关在 JMeter 测试中使用 Beanshell 脚本的更多信息的指南
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)