在 jmeter 中通过 Beanshell 从响应休息服务中获取第一个 json 对象

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

我从我的 Web 服务得到了这个 JSON 响应:

[
    {
        "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,
    },...
]

现在通过 JMeter 中的 Beanshell 我想将第一个 id 传递给新请求,所以在 JSR223 PostProcessor 中我写了一个简单的打印如下:

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);

但我收到了这个错误:

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]

我听说 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 并使用以下单行将第一个 ID 存储到一个变量中:

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

更多信息:Apache Groovy - Parsing and Producing JSON