Search code examples
jmeterjmeter-pluginsjmeter-5.0

Get first json object from response rest service by Beanshell in jmeter


I get this JSON response from my web service:

[
    {
        "type": "022",
        "sendDate": "2020-11-09 12:43:07",
        "message": "test1",
        "id": 8035,
    },
    {
        "notificationType": "023",
        "sendDate": "2020-11-09 11:40:02",
        "message": "test2 ",
        "id": 8034,
    },...
]

Now by Beanshell in JMeter I want to pass first id into new request so in JSR223 PostProcessor i write a simple print like this:

import com.eclipsesource.json.*;
String jsonString = prev.getResponseDataAsString();
log.info("value=" + jsonString);
JsonArray inbox =  Json.parse(jsonString).asArray();
//String id_BSH = ((JSONObject) storeArray.get(0)).getAsString("id");
//vars.put("id_BSH", pickup);

but i got this error :

2020-11-10 17:59:55,245 ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223 PostProcessor
javax.script.ScriptException: Sourced file: inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' : Typed variable declaration : Class: JsonArray not found in namespace : at Line: 4 : in file: inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' : JsonArray 
 in inline evaluation of: ``import com.eclipsesource.json.*; String jsonString = prev.getResponseDataAsStrin . . . '' at line number 4
    at bsh.engine.BshScriptEngine.evalSource(BshScriptEngine.java:93) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
    at bsh.engine.BshScriptEngine.eval(BshScriptEngine.java:46) ~[bsh-2.0b6.jar:2.0b6 2016-02-05 05:16:19]
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233) ~[?:1.8.0_202]
    at org.apache.jmeter.util.JSR223TestElement.processFileOrScript(JSR223TestElement.java:224) ~[ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.extractor.JSR223PostProcessor.process(JSR223PostProcessor.java:45) [ApacheJMeter_components.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.runPostProcessors(JMeterThread.java:940) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:572) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:489) [ApacheJMeter_core.jar:5.3]
    at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:256) [ApacheJMeter_core.jar:5.3]
    at java.lang.Thread.run(Thread.java:748) [?:1.8.0_202]

Solution

  • I've heard Groovy "is the new black", moreover you should not be using Beanshell since JMeter 3.1 so you can go for Groovy's JsonSlurper class and store the first ID into a variable with this one-liner:

    vars.put("id_BSH", new groovy.json.JsonSlurper().parse(prev.getResponseData()).get(0).id as String)
    

    More information: Apache Groovy - Parsing and Producing JSON