首页 > 解决方案 > 将空字符串传递给 Class JsonOutput 方法 toJSON

问题描述

我有这个 Groovy 脚本,我将一个空字符串传递给方法“toJson”(它在 groovy.json.JsonOutput 中)。

我想测试我们的 API 是否正在处理和键入一个空字符串,所以"key": "",

我实际上想测试三件事:

  1. 使用有效值进行测试(“key”:“valid value”)
  2. 用空值测试 ("key": "")
  3. 没有键和值的测试(空)

我使用以下 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)〜[?:?]

有解决此问题的方法吗?

标签: jsongroovygenerator

解决方案


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

推荐阅读