0
votes

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"
 }
1

1 Answers

0
votes

Given you're using JsonBuilder you will have a valid JSON, i.e. starting with { and ending with }.

If for some reason this is something you don't want you can remove starting and trailing curly braces like:

def ctd = vars.get('customertypedetails')
ctd = ctd.substring(ctd.indexOf('{') +1,ctd.lastIndexOf('}'))
vars.put('customertypedetails',ctd)

See Apache Groovy - Why and How You Should Use It article for more information on using Groovy scripting in JMeter tests.