首页 > 解决方案 > JMeter - JSON 响应操作在带有 java 的 JSR223 处理器中不起作用

问题描述

import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;

JSONParser p = new JSONParser(JSONParser.MODE_PERMISSIVE);

String response = prev.getResponseDataAsString();
JSONObject jsonresponse = (JSONObject) p.parse(response);
JSONObject json2 = (JSONObject) jsonresponse.get("Key1");

JSONObject newjson = new JSONObject();
newjson.put("displayValue", json2.get("displayValue"));
newjson.put("value", json2.get("value"));

jsonresponse.put("Key2", newjson);

if(jsonresponse.has("Key3"))
{
    jsonresponse.remove("Key3");
    jsonresponse.put("Key3", jsonresponse.get("Key3").get("value");     
}

log.info(jsonresponse.toString());

我需要进入 if 循环以删除 json 键值(如果存在)并将其替换为其他内容。

标签: jmeterbeanshelljsr223

解决方案


  1. 我相信您至少需要将if(jsonresponse.has("Key3"))线路更改为if(jsonresponse.containsKey("Key3"))
  2. 根据 JMeter 最佳实践,您不应该使用 Beanshell 进行脚本编写,因此请考虑切换到 Groovy 语言,Groovy 的性能要好得多,而且它具有内置的 JSON 解析/生成功能。请参阅Apache Groovy - Why and How You Should Use It文章以获取全面的解释、基准测试、示例代码片段等。

推荐阅读