无法在 JSR 预处理器中针对 Groovy 中的 csv 文件创建正确的 JSON

Unable to create correct JSON against csv file in Groovy within JSR Preprocessor

完全菜鸟 JMeter.Been 尝试使用带有 Groovy 的 CSV 文件创建 json 并在 jmeter 的请求正文中传递相同的文件,但无法创建 JSON格式要求:

Sample2.csv

作品登记 - 外部,3423,115

Jmeter HTTPRequest --JSR223Preprocessor

对于上述csv,JSR223Preprocessor中的以下代码提供输出

import groovy.json.*
def builder = new groovy.json.JsonBuilder()

@groovy.transform.Immutable
class WKList {
    String wkname
    int Wkid
    int numId
}

def WKLists = new File("Sample2.csv")
        .readLines()
        .collect { line ->
            new WKList(Integer.parseInt(line.split(",")[0]), Integer.parseInt(line.split(",")[1])),line.split(",")[2] }

builder(
        Place:'RA',
        Serial: 2,
        SerialDate: 'Dec 30 ,2021',
        WKList: WKLists.collect(),

)
log.info(builder.toPrettyString())

输出: { “地方”:“RA”, “串行”:2, "SerialDate": "2021 年 12 月 30 日", “WK列表”:[ { “孩子”:3423, “编号”:115, "wkname": "工作注册 - 外部" } ] }

前 3 列是硬编码的。 但是如果原始csv文件如下

RA,8,2021 年 12 月 30 日,工作注册 - 外部,3423,233

KA,92,2021 年 12 月 20 日,州注册 - 内部,121,3

如何修改代码以包含来自 csv 的值而不是像之前那样获取硬编码值?此外,如果使用 CSV 数据集配置 JMeter,它是否会在每次迭代中为每个用户读取每行?

这一行看起来很可疑:

new WKList(Integer.parseInt(line.split(",")[0]), Integer.parseInt(line.split(",")[1])),line.split(",")[2] }

您的 WKList class 需要 String as a first parameter followed by 2 Integers

所以我的期望是您应该将其更改为:

new WKList(line.split(",")[0], Integer.parseInt(line.split(",")[1]), Integer.parseInt(line.split(",")[2]))

此外,您的代码采用以下 CSV 文件结构:

Work Registration - External,3423,115

如果需要包含,请使用以下文件格式:

RA,8,Dec 30, 2021,Work Registration - External,3423,233

我们需要知道 JSON 的“所需格式”是什么。

同时您可以熟悉以下内容material:

这适用于 csv 文件行 RA,8,"2021 年 12 月 30 日",工作登记 - 外部,3423,233

import groovy.json.*

class WKList {String wkname; int Wkid ;int numId}
List<WKList> WKDetList = new ArrayList<>();
def lines =new File("Sample2.csv").readLines()

def content = [:]
def articles = []
def article = [:]
for (int i=1;i<lines.size();i++)

{ 
String[] splitData = lines[i].split(',');

content.put('Place', splitData[0])
content.put('Serial', splitData[1])
content.put('SerialDate', splitData[2])
article.put('wkname', splitData[3])
article.put('wkid', splitData[4])
article.put('numId', splitData[5])
articles.add(article)
content.put('WKList', articles)   
  
}
sampler.addNonEncodedArgument('', new groovy.json.JsonBuilder(content).toPrettyString(), '')
sampler.setPostBodyRaw(true)


log.info(JsonOutput.prettyPrint(JsonOutput.toJson(content)))