json - 将空字符串传递给 Class JsonOutput 方法 toJSON
问题描述
我有这个 Groovy 脚本,我将一个空字符串传递给方法“toJson”(它在 groovy.json.JsonOutput 中)。
我想测试我们的 API 是否正在处理和键入一个空字符串,所以"key": "",
我实际上想测试三件事:
- 使用有效值进行测试(“key”:“valid value”)
- 用空值测试 ("key": "")
- 没有键和值的测试(空)
我使用以下 groovy 代码来构建 JSON 主体。在实际脚本中有一些语句,脚本会检查值是否存在,如果不存在,则将其排除。
import groovy.json.*;
class Example {
def exampleKey1
def exampleKey2
def exampleKey3
}
String valueexampleKey1 = "value";
String valueexampleKey2 = "";
String valueexampleKey3 = null;
def generator = new JsonGenerator.Options()
.excludeNulls()
.build()
Example example = new Example (
exampleKey1: valueexampleKey1,
exampleKey2: valueexampleKey2,
exampleKey3: valueexampleKey3
);
String unformattedJSON = generator.toJson(example);
String formattedJSON = JsonOutput.prettyPrint(unformattedJSON);
vars.put("generatedBody", formattedJSON);
抛出以下异常:
2020-02-12 13:05:26,168 错误 oajJMeter:未捕获的异常:java.lang.IllegalAccessError:groovy.json.DefaultJsonGenerator 类试图访问私有字段 groovy.json.JsonOutput.EMPTY_STRING_CHARS(groovy.json.DefaultJsonGenerator 和 groovy.json .JsonOutput 在 groovy.json.DefaultJsonGenerator.writeCharSequence(DefaultJsonGenerator.java:256) ~[groovy-json-2.5.7.jar:2.5.7] 的加载程序 org.apache.jmeter.DynamicClassLoader @1ae369b7) 的未命名模块中groovy.json.DefaultJsonGenerator.writeObject(DefaultJsonGenerator.java:190) ~[groovy-json-2.5.7.jar:2.5.7] at groovy.json.DefaultJsonGenerator.writeMapEntry(DefaultJsonGenerator.java:387) ~[groovy-json -2.5.7.jar:2.5.7] 在 groovy.json.DefaultJsonGenerator.writeMap(DefaultJsonGenerator.java:375) ~[groovy-json-2.5.7.jar:2.5.7] 在 groovy.json。DefaultJsonGenerator.writeObject(DefaultJsonGenerator.java:237) ~[groovy-json-2.5.7.jar:2.5.7] at groovy.json.DefaultJsonGenerator.writeObject(DefaultJsonGenerator.java:164) ~[groovy-json-2.5.7 .jar:2.5.7] 在 groovy.json.DefaultJsonGenerator.toJson(DefaultJsonGenerator.java:98) ~[groovy-json-2.5.7.jar:2.5.7] 在 groovy.json.JsonGenerator$toJson.call(未知来源)~[?:?] at Script27.run(Script27.groovy:111)~[?:?]常规:111)〜[?:?]常规:111)〜[?:?]
有解决此问题的方法吗?
解决方案
import groovy.json.*;
def exampleOne = "";
def exampleTwo = null;
def exampleThree = vars.get("varExampleThree");
def json = new groovy.json.JsonBuilder();
def result = json {
if (exampleOne != null) { keyOne exampleOne }
if (exampleTwo != null) { keyTwo exampleTwo }
if (exampleThree != null) { keyThree exampleThree }
}
vars.put("output", json);
推荐阅读
- java - 计算两条线之间的角度
- graph - 性能 SQL Server 2017 图表与 Neo4j
- javascript - 输入类型=“数字”不适用于货币管道
- sql - 从日期间隔获取总等待时间和行数
- html - 删除背景图片后,Google 表单布局不会重置
- scala - 多个随机 UUID 但值 uuid 相同
- reactjs - 数组或迭代器中的每个孩子都应该有唯一的 key prop reactjs
- date - 获取月末或当前日期+基于当前日期的几天
- shell - awk 乘法给我的值与 2 个数字的正常乘法不同
- java - 是否有任何 java Parser 可用于解析 rabbitmq.conf (erlang) 文件?