This is the request JSON
{
"Transaction": {
"TrType": "Vehicle",
"CustomerType": "${__chooseRandom(Individual,Company,)}",
},
"IndividualClient": {
"firstName": "test first name",
"lastName": "test last name"
}
"CompanyClient": {
"CompanyName": "test company name",
}
}
So if customer type = Individual then generate Individual else generate Company.
I used JSR223 Pre-Processor and in that.
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
def jsonRequest = null
JsonSlurper jsonSlurper = new JsonSlurper()
jsonRequest = jsonSlurper.parseText(sampler.getArguments().getArgument(0).getValue())
println(JsonOutput.prettyPrint(JsonOutput.toJson(jsonRequest)))
if (jsonRequest.Transaction.CustomerType.equalsIgnoreCase("Individual")) {
jsonBuilder = new JsonBuilder()
jsonBuilder.IndividualClient {
firstName "test first name"
lastName "test last name"
}
vars.put("customertypedetails",jsonBuilder.toPrettyString())
println(vars.get("customertypedetails"))
} else {
jsonBuilder2 = new JsonBuilder()
jsonBuilder2.CompanyClient {
companyName "test company name"
}
vars.put("customertypedetails",jsonBuilder2.toPrettyString())
println(vars.get("customertypedetails"))
}
reference link I used for this purpose. https://examples.javacodegeeks.com/jvm-languages/groovy/groovy-json-example/
This ${customertypedetails} i am using in my JSON as;
{
"Transaction": {
"TrType": "Vehicle",
"CustomerType": "${__chooseRandom(Individual,Company,)}",
},
${customertypedetails}
}
But i am getting exception
javax.script.ScriptException: groovy.json.JsonException: expecting '}' or ',' but got current char '$' with an int value of 36
The current character read is '$' with an int value of 36 expecting '}' or ',' but got current char '$' with an int value of 36 line number 32 index number 907 $customertypedetails, ..^ at org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.eval(GroovyScriptEngineImpl.java:320) ~[groovy-all-2.4.13.jar:2.4.13]
When I printed (vars.get("customertypedetails") I am getting
{
"IndividualClient": {
"firstName": "test first name",
"lastName": "test last name"
}
}
instead of
"IndividualClient":
{
"firstName": "test first name",
"lastName": "test last name"
}