Unable to call object from a List located in external BeanShell script [Jmeter]

571 views Asked by At

My end goal here is to get a string from a list that is created dynamically from a JSON response. I am having troubles calling a value from the list that is created in an external BeanShell script. The external script reads the JSON response and creates the list from the filtered response.

import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Filter;

try{

    String json = new String(prev.getResponseDataAsString());

    List allPositiveAffects = JsonPath.read(json, "$.affectTags[?(@.value > 0.0)].key", new Filter[]{});
    vars.putObject("allPositiveAffects",allPositiveAffects);
    log.info("allPositiveAffects: " + allPositiveAffects);

    int positiveAffectCount = allPositiveAffects.size();
    vars.put("positiveAffectCount",Integer.toString(positiveAffectCount));

} catch (Throwable ex){
    log.error("Error:\n", ex);
}

allPositiveAffects returns the expected values, so now I want to get one of those values into a subsequent JSON POST.

My Jmeter test setup:

- Thread Group
  + JSON GET request
    - BeanShell PostProcessor
  + JSON POST request

Attempting to get a value from allPositiveAffects has proven to be not as easy as calling allPositiveAffects.get(n) like I can within my BeanShell script.

I haven't figured out an easy way to get the contents of the Lists. Am I missing something? I have tried several different things in my JSON POST request. The latest being:

//json POST data
{
"entries":[
"id": -1,
"key": "${__BeanShell(${allPositiveAffects}.get(1))}"]
}

Which returns the following error:

java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to java.lang.String

Any help on a solution or workaround for this would be greatly appreciated. It would be a lot easier for me to be able to call a List instead of creating various variables.

1

There are 1 answers

3
Dmitri T On

I believe that you could just add .toString() to your expression like:

`${__BeanShell(${allPositiveAffects}.get(1).toString())}`

By the way, Beanshell has some performance overhead so I would rather suggest going for JSON Path Extractor which is available via Extras with Libs Set of JMeter Plugins package, it should be more convenient and less resource consuming.

See Using the XPath Extractor in JMeter (scroll down to "Parsing JSON") for installation instructions and some JSON Path language reference examples.