Jmeter:在 BeanShell Prepocessor 中解析 JSON 响应并将其存储在变量中

P p*_*tra 3 json jmeter beanshell

Jmeter:如何使用 BeanShell 预处理器从响应中提取和存储 accountID 变量?我们可以为此使用 JSON 或正则表达式。

我的回复看起来像:

    {
   "address":{
      "street1":"6550 Vallejo Street",
      "street2":"",
      "city":"Emeryville",
      "state":"CA",
      "zipcode":"98456",
      "country":"Uk"
   },
   "timezone":"US/Pacific-New",
   "reference":"fe_qa001",
   "token":"ns7h4rqVZegSZG6yZls6",
   "login":"fe_qa001@qa.com",
   "accountId":-9223372036762408565,
   "firstName":"qa029",
   "lastName":"svcqa",
   "email":"fe_qa001@qa.com",
   "component":[
      {
         "type":1,
         "reference":"12-1",
         "version":"1",
         "base":"Plastic",
         "zipcode":"94556",
         "bedsize":"high",
         "bed":false,
         "componentId":0,
         "code":"P5",
         "sku":"abcd",
         "serial":"1234",
         "purchaseDate":1372723200000,
         "chamber":2
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

我是 Jmeter 的新手。所以任何人都可以在这里帮助我。该要求就像从下面给出的响应中提取帐户 ID 并使用 BeanShell 预处理器将其存储在变量中。

Dmi*_*i T 5

我不知道你是从哪里得到这段代码的,但看起来它使用的是minimum-json库并且以一种奇怪的方式使用它,所以

  1. 确保 minimum-json.jar 在 JMeter 类路径中
  2. 您已重新启动 JMeter 以选择 .jar
  3. 你有所有必要的进口

此外,您的代码似乎无法与 minimum-json-0.9.4.jar 一起正常工作,您应该将其修改为:

import com.eclipsesource.json.JsonObject;

String jsonString = prev.getResponseDataAsString(); 
JsonObject accountId = JsonObject.readFrom(jsonString);
vars.put("accountId_BSH",String.valueOf(accountId.getLong("accountId",0L)));
Run Code Online (Sandbox Code Playgroud)

您可以使用JSR223 PostProcessor 和 Groovy 语言更轻松地完成同样的工作。Groovy 具有内置的 JSON 支持,因此您无需添加任何 .jar。参考 Groovy 代码:

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper();
def response = jsonSlurper.parseText(prev.getResponseDataAsString());
vars.put("accountId_BSH", response.accountId.toString());
Run Code Online (Sandbox Code Playgroud)

最好的方法可能是使用自JMeter 3.0以来可用的JSON Path PostProcessor。相关配置将类似于:

  • 变量名称: accountId_BSH
  • JSON 路径表达式: $.accountId

JSON 路径帖子