Reputation: 141
tool_name = 'test
product_name = 'test'
platform_name = 'test'
def my_json = new JsonBuilder()
def root = my_json name: tool_name, product: product_name, platform: platform_name
print my_json
What am I doing wrong? I am trying to create a very basic (flat) json object to later send in a POST request.
something like:
{'name': 'test', 'product': 'test', 'platform': 'test'}
What is the easiest way to do this? Can I use JsonBuilder or Slurper for this? I am completely new to groovy.
Upvotes: 2
Views: 5562
Reputation: 42264
You can simply use a Map
and render it as JSON using groovy.json.JsonOutput.toJson()
helper method, e.g.
def tool_name = 'test'
def product_name = 'test'
def platform_name = 'test'
def map = [name: tool_name , product: product_name , platform: platform_name]
def json = groovy.json.JsonOutput.toJson(map)
println json
This example produces following output:
{'name': 'test', 'product': 'test', 'platform': 'test'}
If you want to use groovy.json.JsonBuilder
then below example produces your expected output:
def tool_name = 'test'
def product_name = 'test'
def platform_name = 'test'
def builder = new groovy.json.JsonBuilder()
builder {
name tool_name
product product_name
platform platform_name
}
println builder.toString()
groovy.json.JsonSlurper
class is dedicated to reading JSON documents and manipulating them if needed.
Upvotes: 4