Extracting JSON Response using Bean Shell Postprocessor

蹲街弑〆低调 提交于 2019-11-30 15:43:03

First of all, why don't you use JSON Path PostProcessor for it? You can get absolutely the same using single simple JSON Path expression like:

$.store[0].pickup

If for any reason you still need to do it in Beanshell I have some ideas:

  1. This is definitely the error. You cannot declare 2 variables with the same name in Beanshell script

    JsonObject store = JsonObject.readFrom(jsonString);
    JsonArray store = store.get("store").asArray(); 
    //        ^^^^^  ka-boom!
    
  2. Possible problem. IndexOutOfBoundsException if there will be only 1 store in the response. In Beanshell collections are zero-based, 1st element will have index of 0.

    String pickup = store.get(1).asObject().get("pickup").asString();
    //                        ^ ka-boom! 
    
  3. Another possible problem could be regarding your imports, just in case

    import org.json.JSONArray;
    import org.json.JSONObject;
    import com.eclipsesource.json.*;
    

    Have you added the relevant jars to JMeter Classpath and have you restarted JMeter after this? Are you sure you're using methods correctly?

Here is your code re-implemented using json-smart which comes with JMeter 3.0 (you don't need any other 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");
}

And the evidence of its work

See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more information on using Beanshell scripting in your JMeter tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!