-1

I have to create a json payload using groovy which will be like-

{
  "source":1,
  "target":0 
}

And the source and target values would change dynamically starting from 0. Can you help me with this?

Rao
  • 20,781
  • 11
  • 57
  • 77

2 Answers2

0

You can use JsonBuilder to create the required json as shown below.

//Define value or assign it dynamically for target and source as shown below
def tValue = 0
def sValue = 1

def json = new groovy.json.JsonBuilder()
json {
  source sValue
  target tValue
}
println json.toPrettyString()

You can quickly try it online demo

Rao
  • 20,781
  • 11
  • 57
  • 77
0

Usually nice to use JsonOutput. You can build json from map:

def map = [source:1, target:0]
def out = new groovy.json.JsonOutput()
println out.prettyPrint(out.toJson(map))
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22